Controlling what gets imported

When you import a module or package, or when you use a wildcard import such as from my_module import *, the Python interpreter loads the contents of the given module or package into your global namespace. If you are importing from a module, all of the top-level functions, constants, classes, and other definitions will be imported. When importing from a package, all of the top-level functions, constants, and so on defined in the package's __init__.py file will be imported.

By default, these imports load everything from the given module or package. The only exception is that a wildcard import will automatically skip any function, constant, class, or other definition starting with an underscore—this has the effect of excluding private definitions from the wildcard import.

While this default behavior generally works well, there are times when you may want more control over what gets imported. To do this, you can use a special variable named __all__.

To see how the __all__ variable works, take a look at the following module:

A = 1
B = 2
C = 3
__all__ = ["A", "B"]

If you imported this module, only A and B would be imported. While the module defines the variable C, this definition would be skipped because it isn't included in the __all__ list.

Within a package, the __all__ variable behaves in the same way, with one important difference: you can also include the name of modules and sub-packages that you want to include when the package is imported. For example, a package's __init__.py file might contain only the following:

__all__ = ["module_1", "module_2", "sub_package"]

In this case, the __all__ variable controls which modules and packages to include; when you import this package, the two modules and the sub-package will be imported automatically.

Note

Note that the preceding __init.py__ file is equivalent to the following:

import module1
import module2
import sub_package

Both versions of the __init__.py file would have the effect of including the two modules and the sub-package within the package.

While you don't need to use it, the __all__ variable gives you complete control over your imports. The __all__ variable can also be a useful way of indicating to users of your modules and packages which parts of your code they should be using: if something isn't included in the __all__ list, then it's not intended to be used by external code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.90.182