Python Package
What are packages?
Files that we have on our computer are not stored in the same location. We usually use an organized hierarchy of directories to save files for easier access.
Similar files are saved in the same directory, for example, we may store all the pictures in the "picture" directory. In the same way, Python has packages for directories and modules for files.
As the program grows more in size with many modules, we put similar modules in one package and different modules in separate packages. This architecture will make the program clear and easy to manage.
Likewise, as a directory in an operating system can contain subdirectories and files, a Python package can have sub-packages and modules.
A directory needs to contain a file name __init__.py
to be considered a package in Python. This file can be left empty, but we often put the initialization code for that package in this file.
Let us suppose we are developing a robot. A possible organization of packages and modules could be shown in the illustration below.

Importing a module from a package
We use the .
operator to import modules from packages.
For example, if we want to import the talk
module above, it can be done as follows.
import Robot.Actions.talk
If this module includes a function named hello()
, we need to use the full name to reference it.
Robot.Actions.talk.hello()
If the call Robot.Actions.talk.hello()
seems lengthy, we can import the module without the package prefix.
from Robot.Actions import talk
And then, we can call the function as follows:
talk.hello()
Another way of importing only the required function (or variable or class) from a module within a package is by typing the following statement.
from Robot.Actions.talk import hello
And then, we can directly call this function without any prefix.
hello()
Even if this method is more straightforward to call a function, it is not recommended because it may cause the same identifier name to collide.
Note: It is recommended to use the full namespace when calling a method (or variable or class) to avoid confusion and prevents same identifier names from colliding.
While importing packages, Python checks in the list of directories defined in sys.path
.