Python user-defined exceptions placement and catching -
I'm new to Python and I'm not sure what is the best place to put an exception defined by my user, and Where to catch them.
For example, I have a program that starts the game, when the game stops, the exception defined by the user is picked (StopGame). After throwing this exception to the game, I should catch the exception from the game outside. However, the exception is specific to the game, so the definition of exception should be in the game module (or perhaps the game package?).
Here is a simple layout of the program:
Program Structure : _ _main_ _ .py game / game.py This code works just like this, I do not know yet That is the way to go, I feel somewhat disappointed that I Need to import all the exceptions in the game setup / _ init _ . Otherwise, I should catch an exception like this: which seems a little bad. I think it is better to be able to get all properties in the module 'Game' from the variable 'Game' in _ Main _ .py. Then I know that you can put it in the game / _ init _ .py: which will import all sections from the game / game.py, but I've heard that using * to import * is a bad practice. So, my question is, what is the best way to do this? My complete setup may be wrong, if so, then I would like to hear what is the correct setup. Thanks a long time ago! BTW: If you are wondering why the game module within the game module: The idea is that the package will consist of a lot of modules related to the game, the game / game.py only the beginner of the whole game Maybe, I should keep that code in play / _ init _ .py? I think the best way to answer your problem is to see a real Python package and how it has been built. I take this example. This module is about creating HTTP requests. You have to play a game. Request the original HTTP request functionality to Exceptions are defined in the The last, no
__ main__.py game / __init__.py Game.py
Import game def main (): g = game.Game () Try: g.start () except game. Close Gamm: Print '\ nby Bye!' If the game imports from __name__ == '__main__': main
game.game.StopGame
by game import
How is it done elsewhere?
/ __init __. Py is imported into the file, but it is defined elsewhere. You are doing this, but there may be a better name in 'elsewhere', maybe a
game / core.py might be a good fit.
requests / exceptions.py file. It is usually suitable for a relatively small package, with all the exceptions being made in one place.
Note that exceptions to requests / __init __ Py is also imported! This makes it easy to import them into other packages, which they may need to catch!
is used by the module import; it can not really take much time to actually add, so you should have
* should avoid.
What can you do in your case?
game / game.py file, call it at
game / core-use
game / exception / file
game / __init __. In Py , import that is usually required by your package: main square and exception.
Comments
Post a Comment