Packages are the way to structure module namespaces.
We generally keep python modules or files in different directories to structure our program, not keeping everything in a single directory
A directory of python code is called a package.
Let us create a python package with some python modules inside it
FIrst of all we need to create a directory called bar.
The name of the directory bar is the name of the package.
Let us create a module foo.py and a special file __init__.py inside it.
NOTE: __init__.py is file need to present inside a directory to make it a python package if you are using python versions < 3.3 (including all 2.X)
__init__.py can be blank.
def printme(): print("Python packages tutorial")
Here bar is the python package and foo is the module inside package.
Python package can have many subdirectories inside it which can be called as python sub packages.
Every sub package should have on __init__.py within it (for < v. 3.3).
Any module and its attributes inside a package can be imported using import or from... import keywords using dotted notations
Let us import the module foo and its definitions present in bar
import bar.foo bar.foo.printme() # prints - Python packages tutorial
We can import the module directly using from..import
from bar import foo foo.printme() # prints - Python packages tutorial
We can also directly import printme() into current namespace as follows
from bar.foo import printme printme() # prints - Python packages tutorial
When we import a module inside a package, python also tries to search package and module within module search paths.
We have to set the proper module search path before importing ( same as discussed in the previous chapter).
For example if the package bar is present inside directory "C:\\code" and we are in a different directory, then we have to set "C:/code" to PYTHONPATH or append to sys.path before import.
C:>set PYTHONPATH=C:\\code C:>python main.py Python packages tutorial
Or at runtime
impot sys sys.path.append('C:\\code') # setting the search path to sys.append import bar.foo bar.foo.printme()
C:>python main.py Python packages tutorial
Let us create a sound package as follows
sound |-- filters | |-- __init__.py | |-- equalizer.py | |-- karaoke.py |-- effects | |-- __init__.py | |-- echo.py | |-- reverse.py |-- formats | |-- __init__.py | |-- mp3.py | |-- mp4.py | | -- __init__.py
The sound package has 3 more sub packages here filters, effects, formats.
All the 3 sub packages has a __init__.py within it, qualifying it to be a python package (not required for > v 3.3+)
We can import these python modules as follows
from sound.filters import equalizer from sound.filters import karaoke from sound.effects import echo from sound.effects import reverse from sound.formats import mp3 from sound.formats import mp4
All the sub package inside the a package can be imported with dotted notation as above