问题
Suppose I import the following two modules as follows:
from sympy import *
from numpy import *
both modules have an exp() function defined. How does python pick which one to use? Is there a way to distinguish these functions after the modules have been imported as above? What mechanism exists to warn the user when this is the case? Consider the following set of commands in IDLE
=============================== RESTART: Shell ===============================
>>> from sympy import *
>>> from numpy import *
>>> exp(5)
148.4131591025766
>>> c = symbols('c')
>>> exp(c)
Traceback (most recent call last):
File "<pyshell#162>", line 1, in <module>
exp(c)
AttributeError: 'Symbol' object has no attribute 'exp'
>>>
=============================== RESTART: Shell ===============================
>>> from sympy import *
>>> c = symbols('c')
>>> exp(c)
exp(c)
It appears that by default python uses the exp() definition in numpy however when it is called on an object type recognized by sympy it throws an error which renders the sympy.exp() function unuseable.
For this case, I know that the functions exist in both packages but what if I don't? There ought to be some mechanism that warns the user to avoid really confusing situations.... How does the python community deal with this issue?
回答1:
It doesn't "pick". When you do from sympy import * it imports all names from sympy into the current namespace; and when you do from numpy import * it does the same thing. Anything that is previously defined is overwritten. This is exactly the same as if you did:
foo = 'bar'
foo = 'baz'
Clearly, foo now has the value "baz" even though you initially defined it as "bar".
The solution is not to do this; you should import the things you need explicitly:
from sympy import exp, ....
from numpy import ....
回答2:
As far as I know and according to your code, the numpy's exp() would be added to your namespace as it's the last module which was imported. So, in this case, the last one wins the race! To fix this just use :
from toys import yo-yo as yo-yo1
来源:https://stackoverflow.com/questions/45502124/on-import-modules-and-method-names-in-python