Modules & Scopes

Modules or Packages

They are created by adding a __init__.py file inside a folder named <your-package-name>.

├── /<package-name>
  ├── __init__.py
  ├── ...

Submodules are created the same way. They are only packages inside other packages.

├── /<package-name>
  ├── __init__.py
  ├── ...
  ├── /<subpackage-name>
    ├── __init__.py
    ├── ...

__init__.py

Inside this file you may:

  • Package initialization code: Code that should run when the package is imported. (Like setting up logging, loading configuration, or initializing package-level variables)

  • Expose submodules or functions.

  • Defining __all__.

  • Add version information. (With __version__)

Exposing submodules

You can import submodules, classes, or functions so they are available directly from the package. This is called explicit re-exporting.

E.g., suppose you have a package main that has two subpackages sub1 and sub2.

When outside, user can:

__all__

With __all__ you can specify which function of your module will be "exported", when calling for from module import *.

This is only at a namespace level.

And it does not prevent direct imports.

Visibility in python

In Python everything is public by default.

You can use the underscore convetion, by prefixing a name with an underscore (e.g., _my_func), to hint users that it is "private".

But this is only convention, it does not prevent access.

Importing packages

Scope in Python

Variable creation is limited by the scope of where it is created.

A variable created in the main body of the Python code is a global variable and belongs to the global scope.

Global variables

Creating or referencing global variables inside blocks can be done with global keyword.

Non-local variable reference

Using nonlocal to a variable will make the reference to the variable be of the outer scope.

Useful with nested functions.

Last updated