Organization of my Python project

I am starting a Python project and expect it to have 20 or more classes. As a good practice, I want to put them in a separate file each. However, the project directory is quickly overloaded with files (or will be when I do this).

If I put the import file in a folder, I can no longer import it. How to import a file from another folder and I will need to refer to the class that it contains differently, now that it is in the folder?

Thank you in advance

+44
python project-organization
Dec 24 '08 at 17:23
source share
4 answers

Create the __init__.py file in your projects folder and it will be considered as a Python module.

Classes in your package directory can be imported using the following syntax:

 from package import class import package.class 

In __init__.py you can create an __all__ array that defines the behavior from package import * :

 # name1 and name2 will be available in calling module namespace # when using "from package import *" syntax __all__ = ['name1', 'name2'] 

And here is a lot more information than you even want to know about packages in Python

Generally speaking, a good way to learn how to organize a lot of code is to choose the popular Python package and see how they did it. I would check out Django and Twisted , for starters.

+31
Dec 24 '08 at 17:31
source share

"As a good practice, I want to put them in a separate file each."

This is not a good practice. You must design modules that contain closely related classes.

As a practical matter, not a single class is completely alone. Typically, classes belong to clusters or groups that are logically related.

+22
Dec 24 '08 at 17:42
source share

Python does not force you to embed Java style in one class. In fact, he did not even consider it a good style to put each class in a separate file, if they are not huge. (If they are huge, you probably have to do refactoring). Instead, you should group similar classes and functions in modules. For example, if you are writing a GUI calculator, your package layout might look like this:

 /amazingcalc /__init__.py # This makes it a Python package and importable. /evaluate.py # Contains the code to actually do calculations. /main.py # Starts the application /ui.py # Contains the code to make a pretty interface 
+12
Dec 24 '08 at 17:33
source share

the simple answer is to create an empty file named __init__.py in the new folder that you created. Then, in your top level .py file, include something like:

 import mynewsubfolder.mynewclass 
+6
Dec 24 '08 at 17:33
source share



All Articles