Difference between “import X” and “from X import *

2019-01-11 22:46发布

问题:

This question already has an answer here:

  • Use 'import module' or 'from module import'? 13 answers

In Python, I'm not really clear on the difference between the following two lines of code:

import X

or

from X import *

Don't they both just import everything from the module X? What's the difference?

回答1:

After import x, you can refer to things in x like x.something. After from x import *, you can refer to things in x directly just as something. Because the second form imports the names directly into the local namespace, it creates the potential for conflicts if you import things from many modules. Therefore, the from x import * is discouraged.

You can also do from x import something, which imports just the something into the local namespace, not everything in x. This is better because if you list the names you import, you know exactly what you are importing and it's easier to avoid name conflicts.



回答2:

import X: this imports everything as X.var1,X.var2,etc

from X import * : this imports everthing as var1,var2 etc ,i.e it floods the local namespace

see the difference after two calls:

>>> import math
>>> len(globals())  
5                          #no of variables in namespace
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'math': <module 'math' from '/usr/local/lib/python2.7/lib-dynload/math.so'>, '__package__': None}
>>> 
>>>
>>> from math import *
>>> len(globals())
47                     #no of variables in namespace
>>> globals()
{'pow': <built-in function pow>, 'fsum': <built-in function fsum>, 'cosh': <built-in function cosh>, 'ldexp': <built-in function ldexp>, 'hypot': <built-in function hypot>, 'acosh': <built-in function acosh>, 'tan': <built-in function tan>, 'asin': <built-in function asin>, 'isnan': <built-in function isnan>, 'log': <built-in function log>, 'fabs': <built-in function fabs>, 'floor': <built-in function floor>, 'atanh': <built-in function atanh>, 'sqrt': <built-in function sqrt>, '__package__': None, 'frexp': <built-in function frexp>, 'factorial': <built-in function factorial>, 'degrees': <built-in function degrees>, 'pi': 3.141592653589793, 'log10': <built-in function log10>, '__doc__': None, 'math': <module 'math' from '/usr/local/lib/python2.7/lib-dynload/math.so'>, 'asinh': <built-in function asinh>, 'fmod': <built-in function fmod>, 'atan': <built-in function atan>, '__builtins__': <module '__builtin__' (built-in)>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'ceil': <built-in function ceil>, 'atan2': <built-in function atan2>, 'isinf': <built-in function isinf>, 'sinh': <built-in function sinh>, '__name__': '__main__', 'trunc': <built-in function trunc>, 'expm1': <built-in function expm1>, 'e': 2.718281828459045, 'tanh': <built-in function tanh>, 'radians': <built-in function radians>, 'sin': <built-in function sin>, 'lgamma': <built-in function lgamma>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'modf': <built-in function modf>, 'exp': <built-in function exp>, 'acos': <built-in function acos>, 'log1p': <built-in function log1p>, 'gamma': <built-in function gamma>}


回答3:

import X

Creates a label in the local namespace that references the module object.

from X import *

Creates a label for every member attribute of the X module, directly in the local namespace.

Both operations add X to sys.modules, true, but the effect on the local namespace is the difference.



回答4:

There are differences, some simple, others requiring more explanation.

import X just imports the entire module (read: "runs the module"), and assigns it a name in the local scope. The name can be aliased like so: import X as Y

from X import * imports all of the attributes of module X into the local scope, by default. Here's an example of different usage:

# Assume that module `X` contains an `opendb` function
import X
X.opendb('Y')

# VS.
from X import *
opendb('Y')

Where this gets slightly more complicated is when a module defines __all__. This changes the semantics of from X import * to mean "import everything that is listed in the __all__ property." This allows module writers to have control over which functions and objects are exported from their module.



回答5:

You should never use from X import * unless you really know what you're doing. You can get symbols from module X that conflict with symbols from another module or even your own program. The only exception I have to that rule is sometimes from math import *.

You can use the form from X import y to get a single thing from a module.

If you use the import X form, not only do you make your usage of the module explicit X.y but you can now use the reload function if you make changes to the module and need to reimport it.



回答6:

from X import * imports all elements from the module X into the current namespace. import X imports X but doesn't "merge" the namespaces. E.g.:

Module X:

def foo(): pass
BAR = 12

Your code:

from X import *
foo() # calls X.foo
print BAR # prints 12

Or:

import X
X.foo()
print X.BAR


回答7:

Let's use this as an example of our module definition

def my_func():
    return 1

the from import will pull everything into the current namespace

from X import *
print my_func()

the normal import will create a module object called X in the current namespace

import X
print x.my_func()

in addition with from X import my_func can be used to only import that functionality.



标签: python import