Namespace packages in Python

Namespace packages are package that has several logical sub directories inside a module to organize a large module.

They do not have __init__.py to avoid complex initialization ordering problems. hence, they can not have package level initialization code. Nothing will be executed when it is imported.

How does loading of normal and namespace packages works?

  • Pyhton scans all paths in sys.path
  • if  a directory with __init__.py is found, it is loaded a normap package
  • if any file with .py extension, that can act as moduke, is found, it is loaded
  • Finally, all matching directories in sys.path ares considered as namespace package, and one that matches as import name, will be loaded as namespace package

Example:

mkdir directory0 directory1
mkdir directory0/travel_mode
mkdir directory1/travel_mode
mkdir directory1/travel_mode/ships
mkdir directory0/travel_mode/trains

python>>>

import sys
sys.path.extend(['directory0','directory1'])
sys.path
Out[11]:
['/home/nansari/py/reader/compressed',
 '/home/nansari/py/reader/compressed',
 '/home/nansari/py',
 '/home/nansari/anaconda3/lib/python37.zip',
 '/home/nansari/anaconda3/lib/python3.7',
 '/home/nansari/anaconda3/lib/python3.7/lib-dynload',
 '',
 '/home/nansari/anaconda3/lib/python3.7/site-packages',
 '/home/nansari/anaconda3/lib/python3.7/site-packages/IPython/extensions',
 '/home/nansari/.ipython',
 'directory0',
 'directory1']

import travel_mode
travel_mode.__path__
Out[14]: _NamespacePath(['directory0/travel_mode', 'directory1/travel_mode'])

 



Comments

Popular posts from this blog

Python programming language : quick and easy recipes

Creating a package in Python

How does yaml data look when converted in python data structure?