import X
: Esto importa todo como X.var1
, X.var2
, etc
from X import *
: Esto importa Everthing como var1
, var2
etc, es decir, que inunda el espacio de nombres local de
ver la diferencia después de dos llamadas:
>>> 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>}
¿Cómo sabes que hay una diferencia? – eboix
Creo que es en gran medida un problema de espacio de nombres ... 'Importar X' le permite mantener espacios de nombres separados ... mientras' de X import * 'los coloca en el espacio de nombres local –
Si no sabe qué' de X importar * 'las importaciones no lo usan. Si sabes lo que importa ... no lo uses. Estás contaminando tu espacio de nombres. – Matthias