My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming. No Comments on Packages in Python Programming



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:



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 file inside it. In the package CustomMath, a single module named BasicMath is created which contains three functions as follows:



A new Python script is written which uses our custom package named CustomMath as follows:



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:



To see the list of existing packages, we write:



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
  • email
  • 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:



Related Links:

Popular Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up