Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Subtle difference between packages

Subtle differences in loading packages

PEP-420 is explaining the differences between regular packages and namespace packages: https://www.python.org/dev/peps/pep-0420/

Python 2.7

A package with a __init__.py:

my
├── package
│   ├── some_module.py
│   └── __init__.py
>>> import importlib
>>> import os
>>> print(os.path.exists('my/package/__init__.py'))
True
>>> m = importlib.import_module('my.package')
>>> print(m.__path__)
['my/package']

A package without a __init__.py:

my
├── package
│   └── some_module.py
>>> import importlib
>>> import os
>>> print(os.path.exists('my/package/__init__.py'))
False
>>> m = importlib.import_module('my.package')
>>> print(m.__path__)
['my/package']

Python 3.5

A package with a __init__.py:

my
├── package
│   ├── some_module.py
│   └── __init__.py
>>> import importlib
>>> import os
>>> print(os.path.exists('my/package/__init__.py'))
True
>>> m = importlib.import_module('my.package')
>>> print(m.__path__)
['/Users/elbaschid/my/package']

A package without a __init__.py:

my
├── package
│   └── some_module.py
>>> import importlib
>>> import os
>>> print(os.path.exists('my/package/__init__.py'))
False
>>> m = importlib.import_module('my.package')
>>> print(m.__path__)
_NamespacePath(['/Users/elbaschid/my/package'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment