- We don't usually store all of our files on our computer in the same location.
- We use a well-organized hierarchy of directories for easier access.
- Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory.
- Analogous to this, Python has packages for directories and modules for files.
- As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages.
- This makes a project (program) easy to manage and conceptually clear.
- Similarly, as a directory can contain subdirectories and files, a Python package can have sub-packages and modules.
- A directory must contain a file named __init__.py in order for Python to consider it as a package.
- This file can be left empty but we generally place the initialization code for that package in this file.
Example
Importing a Module from a Package
Now, to test our package, invoke the Python prompt from the MyApp folder.
D:\MyApp>python
Import the functions module from the mypackage package and call its power() function.
>>> from mypackage import functions
>>> functions.power(3,2)
9
It is also possible to import specific functions from a module in the package
>>> from mypackage.functions import sum
>>> sum(10,20)
30
>>> average(10,12)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
NameError: name 'average' is not defined