Modules & Packages

09_modules

Modules & Packages

Python files are modules. A folder of Python files (with one special file added: __init__.py) is a package. The assignment folder of this guide is a package. The init file is a python file that exists to mark a folder as a Python package. It is not required to be empty, but it generally is. Packages have the advantage of allowing the import of all the files at once, rather than each file individually.

Python Import | python.org

Import This – Prefered

This is by far the best way to handle imports. Contrary to popular belief – this does not waste memory. All import styles use almost exactly the same amount of memory. All of them will excecute and import the entire namespace of the target, even when it doesn’t seem like it. The names are there, in memory no matter which style you choose – but they may or may not be injected into your namespace. This choice is not about memory, it’s about namespace clutter. The following example is prefered because it causes the least namespace clutter.

In [0]:
import random
In [2]:
print(random.randint(1, 6))
4

From That Import This – Acceptable

This style might be the most common import style. It offers a more convienient calling signature for the names that get imported. While this example doesn’t have the problems of the next example, it still has issues. For one, everything you import like this will be added to the top level of your namespace. At small scale this is not a problem, but it can become a problem if you have many imports in a large project.

This style has the added benifit of listing all the names you intend to use at the top of your module. However, if later you want to use some other part of the module you have to scroll up add that to the import statement, then scroll back down to your code. Small project – no big deal, large project – major pain. Some IDEs can handle imports for you, and this can give you the best of all worlds.

In [0]:
from random import randint
In [4]:
print(randint(1, 6))
1

Star Import – Ugly

The star import can get you in trouble because when you star import multiple modules you loose encapsulation of those modules. This can also pollute your namespace. In the example below all we need is the randint() function – but we’ve imported all the names in the random module to the top level of our namespace. Best case: we have a cluttered namespace. Worse case: we can no longer be sure that we’re not creating name conflicts. Don’t use star imports in production code. It’s fine if it’s the only import in a single module, but it’s still bad form.

In [0]:
from random import *
In [6]:
print(randrange(2, 11, 2))  # random integer in range [2, 10] by 2
4