Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top