Contents
Introduction
A package is a directory structure which can contain modules and sub packages. Every package in Python is a directory which must contain a special file called __init.py__. The file __init.py__ can be empty. To allow only certain modules to be imported, we can use the __all__ variable in __init.py__ file as follows:
1 |
__all__ = [“Stat”] |
The above line says that only Stat module in the package can be imported.
Every package must be a folder in the system. Packages should be placed in the path which is pointed by sys.path. If the package is not available, then ImportError is raised.
Creating a Package
A package (folder) named CustomMath is created with an empty __init__.py file inside it. In the package CustomMath, a single module named BasicMath is created which contains three functions as follows:
1 2 3 4 5 6 7 8 9 |
def prod(x, y): return x*y def rem(x, y): return x%y def lastdigit(x): return x%10 |
A new Python script is written which uses our custom package named CustomMath as follows:
1 2 3 4 |
from CustomMath.BasicMath import * print(prod(4,3)) print(rem(4,3)) print(lastdigit(99)) |
PyPI and Pip
Third party packages are available in Python Package Index (PyPI). We can import the modules available in the third party packages by using the pip tool. Pip is a command line tool for maintaing Python packages.
To install a package using pip we write:
1 |
pip install package-name |
To see the list of existing packages, we write:
1 |
pip list |
Standard Library Modules
Python comes with several built-in modules. We can use them when necessary. These built-in modules forms the Python’s standard library. Some of the modules in standard library are:
- string
- re
- datetime
- math
- random
- os
- multiprocessing
- subprocess
- json
- doctest
- unittest
- pdb
- argparse
- socket
- sys
globals(), locals(), and reload()
The globals() function returns all the names in the global namespace that can be accessed from inside a function.
The locals() function returns all the names in the local namespace i.e., within the function. Both the above functions returns the names as a dictionary.
The reload() function can be used to reload a module again the program if need as follows:
1 |
reload(module_name) |
Leave a Reply