How does Python handle imports?

This is a topic that I discussed in the following youtube video (unfortunately only in brazilian portuguese)

Como python faz imports - youtube video
Como python faz imports - youtube video

These notes were extracted from my github repo https://github.com/Dpbm/video-python-import-methods, take a look if you want more details and some code ;)


Notes

C includes

headers (.h files)

#include

Wrappers

#ifndef DEFINITION_OF_HEADER
#define DEFINITION_OF_HEADER

...

#endif 

JS

Common JS

ES modules


Python import

The import statement

  1. find a module and loads it.
  2. define a name for this module in the current scope.

The import statement using from

  1. find the module specified in from clause.
  2. for each name in import check if the name exists. If not, check if it’s a submodule. If not found raise ImportError. Otherwise import to the local namespace.

using *

Relative imports

PYTHONPATH

sys.path

sys.modules

sys.meta_path (meta hooks)

sys.path_hooks

Modules

__pycache__

Packages

Regular Packages

Namespace Packages

__init__.py

Import Protocol

finders

loaders

Overall Execution pipeline (Default pipeline as I understood)

References