Python packages
Read: Packages
A Python file can be a module but when this file is in a folder, we call this folder a package.
File organization is really important in a big project. This means for Python: packages everywhere.
Compare with C
(file organization, not prototype vs code etc.)
In C:
In Python:
In C:
In Python:
or
Dotted module names == Path
Let's take this example of file organization
How can I use my function my_abs(a) from the file abs.py in my my_script.py
_____
_____
_____
but you will use your function like that:
_____
now you can use your function like that:
_____
Wait, does this really work?
NO! something is missing: the magic file __init__.py
Indeed, each folder must contain this file to be considered a package.
This file should be empty except if you want to import all the content of modules by using *
More complicated?
How can I use my function my_add(a, b) from the file add.py in my_script.py
Easy right?
import * is dangerous
Using import * is still considered bad practice in production code. In that case, __init__.py shouldn’t be empty but must contain the list of modules to load:
Relative versus Absolute import
In this example
positive.py contains one function def is_positive(n) and this function uses my_abs(n). How it’s possible?
By importing:
or
What the difference?
from abs import my_absis using a relative path between your file who imports and the module to importfrom my_math.abs import my_absis using an absolute path between the file you execute and the module to import
$ cat my_script.py from my_math.positive import is_positive print(is_positive(89)) print(is_positive(-89)) print(is_positive(333)) $ python3 my_script.py True False True $
Now, let’s execute a file in my_math:
Ahh! If you are using an absolute path, you can’t execute this module from another point as the “root” of your project.
Let's change to relative path: