I'm getting started with Python (it's high time I give it a shot), and I'm looking for some best practices.
My first project is a queue which runs command-line experiments in multiple threads. I'm starting to get a very long main.py
file, and I'd like to break it up. In general, I'm looking for: How do python programmers organize multiple source files? Is there a particular structure that works for you?
My specific questions include:
I can probably draw some of my own conclusions here by trial and error, but I'd rather start from something good.
Keeping your code in the same file as it grows makes your code difficult to maintain. 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.
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code.
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.
The article Eric pointed to is awesome because it covers details of organising large Python code bases.
If you've landed here from Google and are trying to find out how to split one large source file into multiple, more manageable, files I'll summarise the process briefly.
Assume you currently have everything in a file called main.py
:
utils.py
for this example)main.py
into utils.py
main.py
add a single line at the top: import utils
Conceptually what this does is to create a new module called utils
in another source file. You can then import it wherever it's needed.
The way you should organise your code and tests is exactly the same you would for any OO language.
Answers from the way I do it. It may not be right but works for me
> Workspace > | > |-Src > | |-Package1 > | |-Package2 > | |-main.py > |-Test > |-TestPackage1 > |-TestPackage2
__init__.py
files are in the folders. its just a simple case of from module import class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With