wow yoo wow yoo - 1 year ago 60
Python Question

What is the exact semantic of "from ... import" starement?

I've experiment with the statement,however the result did not match the official description.
Quotation is below:

The from form uses a slightly more complex process:

  1. find the module specified in the from clause, loading and initializing it if necessary;

  2. for each of the identifiers specified in the import clauses:

    1. check if the imported module has an attribute by that name

    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute

    3. if the attribute is not found, ImportError is raised.

    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

I created a namespace package named l007, within which submodule named l009 was placed.I typed "from l007 import l009" in the interpreter, the execution was ok, while in which case a ImportError should have been raised.
Is my understanding wrong?

Answer Source

See this documentation:

When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in __import__()) a binding is placed in the parent module’s namespace to the submodule object. For example, if package spam has a submodule foo, after importing, spam will have an attribute foo which is bound to the submodule.

That is why the steps in your quote are in the order they are in. Even though l007 doesn't initially have an attribute l009, it will have one after the submodule import occurs.

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