Question about "import" / "from import"

0

I do not understand why, with some third-party modules that I use, when trying:

import foo

does not let me access foo.bar ;

however, when using from foo import bar

Yes I can correctly access bar

Why is this happening?

    
asked by psy 17.05.2018 в 23:33
source

1 answer

0

Assuming that bar is a module or package foo , there is no difference, it does not matter. The two statements have exactly the same result:

import foo.bar.bazaar as baz
from foo.bar import bazaar as baz

The import ... as requires that the foo.bar module be injected into the foo space as the bar attribute, in addition to being sys.modules , while the from ... import ... as looks for foo.bar in% sys.modules .

(Note also that import foo.bar only ensures that the module foo.bar is within sys.modules and accessible foo.bar , but not yet fully initialized)

Another Example:

>>> import os.path as path
>>> path
<module 'posixpath' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/posixpath.pyc'>
>>> from os import path
>>> path
<module 'posixpath' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/posixpath.pyc'>

If bar is not a module or package, the second form will not work; instead, a traceback is launched:

>>> import os.walk as walk
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named walk
  

Source SO: from ... import OR import ... as for modules

The difference between import module and from module import foo is mainly subjective. Choose the one you like the most and be consistent in your use of it. Here are some points to help you decide.

import module

  • Pros:

    • Less maintenance of your statements import . It is not necessary to add any additional import to start using another element of the module
  • Cons:

    • Writing your code module.foo can be tedious and redundant (tedium can be minimized by using import module as mo and then typing mo.foo )

from module import foo

  • Pros:

    • Less typing to use foo

    • More control over what elements of a module can be accessed.

  • Cons:

    • To use a new module element, you must update your import declaration.

    • You lose the context about foo . For example, it is less clear ceil() what it does in comparison conmath.ceil() .

Either method is acceptable, but do not use it from module import .

For any large reasonable set of code, if it is likely that import * is consolidating it in the module, it can not be deleted. This is because it is difficult to determine which elements used in the code come from 'module', which makes it easy to get to the point where you think you no longer use import , but it is extremely difficult to be sure.

  
    
answered by 17.05.2018 в 23:49