Skip to content

Instantly share code, notes, and snippets.

@roadsideseb
Last active December 9, 2016 19:24
Show Gist options
  • Save roadsideseb/b0d556139290df92d678bbba9ec2cf01 to your computer and use it in GitHub Desktop.
Save roadsideseb/b0d556139290df92d678bbba9ec2cf01 to your computer and use it in GitHub Desktop.
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