It boils down to two things:
-
__import__is a Python function that will import a package using a string as the name of the package. It returns a new object that represents the imported package. Sofoo = __import__('bar')will import a package namedbarand store a reference to its objects in a local object variablefoo. -
From setup utils pkg_resources’ documentation,
declare_namespace()“Declare[s] that the dotted package name name is a “namespace package” whose contained packages and modules may be spread across multiple distributions.”
So __import__('pkg_resources').declare_namespace(__name__) will import the ‘pkg_resources’ package into a temporary and call the declare_namespace function stored in that temporary (the __import__ function is likely used rather than the import statement so that there is no extra symbol left over named pkg_resources). If this code were in my_namespace/__init__.py, then __name__ is my_namespace and this module will be included in the my_namespace namespace package.
See the setup tools documentation for more details
See this question for discussion on the older mechanism for achieving the same effect.
See PEP 420 for the standardized mechanism that provides similar functionality beginning with Python 3.3.