
PYTHON — Working with Python Packages
The best method for accelerating a computer is the one that boosts it by 9.8 m/s². — Anonymous
Working with Python Packages
Python packages are a way of structuring Python’s module namespace by using “dotted module names.” A package is a directory that can contain sub-packages and modules. In this tutorial, you’ll learn how to work with packages in Python.
To see how importing a module from a package works, create another IDLE editor window. You will create a calling module. At the beginning of the file, import the package with import mypackage. Save this file as main.py in the parent folder of the package.
Run main.py and observe that importing your package works. Then, add the following code to main.py:
import mypackage.module1
import mypackage.module2
mypackage.module1.greet("Cedar")
mypackage.module2.depart("boredom")Save and run main.py again, and observe that both greet() and depart() get called.
The reason for the error in the previous step is that when you import the mypackage module, the module1 and module2 namespaces aren’t imported automatically. Therefore, you need to import them too.
Under the hood, modules are imported from packages using dotted module names with the following format: import <package_name>.<module_name>.
So, for both import statements, the package name is mypackage, followed by a dot, and then the name of the module you want to import.
As with modules, there are several variations on the import statement that you can use when importing packages.
By explicitly importing the sub-modules of a package, you can avoid AttributeError and successfully call the functions and classes defined in those modules.
Packages are a powerful way to organize your Python code. By understanding how to create and import packages, you can better structure your code and make it more modular and reusable.
In conclusion, working with packages in Python involves understanding how to import modules from packages using dotted module names and using various import statements to access the functionality within those modules.
