How to use a built-in function if its name is used by another module?

隐身守侯 提交于 2019-12-24 05:24:12

问题


For example, there is a built-in function any in Python. The problem is, when the module numpy is imported, the definition of function any is changed.

How can I used the original function any in the __builtin__ module?

For example:

from numpy import *
any(i % 3 for i in [3, 3, 4, 4, 3])

and the code will not work! Sorry I am a newbie in Python.


回答1:


You can still reach the object on the __builtin__ module:

import __builtin__
__builtin__.any(i % 3 for i in [3, 3, 4, 4, 3])

(The module was renamed to builtins in Python 3; underscores removed, made plural).

You could assing any to a different name before you import all from numpy:

bltin_any = any
from numpy import *

bltin_any(i % 3 for i in [3, 3, 4, 4, 3])

or don't use import *. Use import numpy as np perhaps, and use np.any() to use the NumPy version that way.




回答2:


You should try to avoid using from name import *. Because of that problem it is really looked down upon to do that.

import numpy as np
np.any(i % 3 for i in [3, 3, 4, 4, 3])

This way you know exactly what you are using and where it came from. It is more readable and understandable.

from name import *

This is really bad, because you have no idea what you are importing. If there are several modules in the package that you don't use it will import them all. You only want what you need to use. Some libraries can get really big which would add a lot of things you don't need.



来源:https://stackoverflow.com/questions/23562849/how-to-use-a-built-in-function-if-its-name-is-used-by-another-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!