What does `__import__(‘pkg_resources’).declare_namespace(__name__)` do?

It boils down to two things:

  1. __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. So foo = __import__('bar') will import a package named bar and store a reference to its objects in a local object variable foo.

  2. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)