How Package, Module, and Import Work in Python - Links to Official Documents
Created On: 2016-11-27
Packages and Modules are major ways of organizing python code. Before you grow big, you should have a good understanding on them.
I have planned to write a post on how these things work in Python, only to find that the official documents are good enough. (I forgot how I learned them since it has been too long.)
So if you want to learn about:
- Why should I define modules and packages?
- How can I define a module or a package?
- How to initialize a module or package?
- How can I import a module in the same package?
- How can I import a module from another package?
- What is relative import? What is absolute import?
- How does
from foo import *
work? - How does python find which module to import in filesystem?
- What is PYTHONPATH and sys.path?
You may read the official document for Modules. Here are the links:
That's a good starting point of understanding packages and modules in python. There are a few more things you may want to know though.
- How to make your package installable? How to distribute your package on PyPI?
Read Distributing Python Modules and Packaging and Distributing Projects.
- What is site-packages? What exactly does install a package do?
- How to build a simple plug-in system using python modules?
The idea is to define a plugin convention (an API that all plug-ins should implement), then query and load modules at runtime. You can load modules at runtime using
importlib.import_module()
. - How to create python module using C, C++ or cython?