rsk rsk - 1 year ago 121
Python Question

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

In some
files of modules I saw such single line:


What does it do and why people use it? Suppose it's related to dynamic importing and creating namespace at runtime.

Answer Source

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 PEP 382, declare_namespace() "is a mechanism for splitting a single Python package across multiple directories on disk."

So __import__('pkg_resources').declare_namespace(__name__) will import all of the symbols from the 'pkg_resources' package and then add them to a namespace whose name is stored in __name__. If this code were in my_namespace/, then __name__ is my_namespace and the symbols in pkg_resources are being added to a namespace package named my_namespace. __import__ is used rather than import so that there is no extra symbol left over named pkg_resources.

See this question for discussion on the older mechanism for achieving the same effect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download