Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organising my Python project

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

If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?

Thanks in advance

like image 754
Teifion Avatar asked Dec 24 '08 17:12

Teifion


People also ask

How do you organize a Python project?

Organize your modules into packages. Each package must contain a special __init__.py file. Your project should generally consist of one top-level package, usually containing sub-packages. That top-level package usually shares the name of your project, and exists as a directory in the root of your project's repository.

How is Python organized?

At this point, Python modules and packages help you to organize and group your content by using files and folders. Modules are files with “. py” extension containing Python code. They help to organise related functions, classes or any code block in the same file.

What is the best project structure for a Python application?

Python doesn't have a distinction between /src , /lib , and /bin like Java or C has. Since a top-level /src directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application. I recommend putting all of this under the "name-of-my-product" directory.


1 Answers

Create an __init__.py file in your projects folder, and it will be treated like a module by Python.

Classes in your package directory can then be imported using syntax like:

from package import class import package.class 

Within __init__.py, you may create an __all__ array that defines from package import * behavior:

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

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

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

like image 195
Kenan Banks Avatar answered Sep 27 '22 17:09

Kenan Banks