Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize my Python code into multiple classes?

I was recently told that I should keep my code in separate files; like main.py, engine.py, settings.py and so on. Although this surely does have benefits, like easier management, scalability and others, to me it seems like it has too many drawbacks...

For example, if I have a script called settings.py, where some things like sizes of onscreen objects, speed of the simulation and color of various objects are defined, what do I do if those variables are needed both in my engine.py script and my main.py script? Do I import it two times, in both scripts? It seems rather messy. What if some of my classes, that are in the engine.py script, require code from main.py?

Let me show you the exact situation...

My main.py script imports Pygame in itself, initializes it, and so on. It used to have a class which represented an onscreen object, and that class had a method draw, which just called a Pygame draw function. Now, when I put the class inside my engine.py script, things no longer work, because Pygame doesn't exist there! I ended up importing both settings.py and Pygame in the engine.py, and then importing the engine into main.py, but then it's more like an initializer than an engine... Is there a way to deal with things like these, like general guide lines?

like image 401
corazza Avatar asked May 08 '12 13:05

corazza


2 Answers

Here are the official PEP guidelines for imports: http://www.python.org/dev/peps/pep-0008/#imports

Also please see this StackOverflow question: What are good rules of thumb for Python imports?

You can import a variable from more than one class without a problem but you should try and structure your code so that things aren't circularly imported. Circular import dependency in Python

like image 75
funkotron Avatar answered Sep 21 '22 18:09

funkotron


Its common practice in other languages (especially Java, where its practically forced by the compiler) to have one file per class.

As for the inter-file dependencies you mention, you should consider avoiding global variables.

Here's another related question that better answers your question.

How many Python classes should I put in one file?

like image 37
Brady Avatar answered Sep 23 '22 18:09

Brady