Modules & Scopes

The use of __name__ == '__main__'

Adding this to a python file script will ensure that everything inside this condition will be only ran, if the script file was runned directly.

if __name__ == '__main__':

This happens because when you import functions from other files, python runs the entire file. So if you have code executing there, it will execute it on the import.

To avoid this you put this code inside this condition.

Modules or Packages

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

triangle-exclamation
├── /<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
    ├── ...
circle-exclamation

__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 *.

circle-info

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.

circle-info

Useful with nested functions.

Last updated