英文:
all(map) and any(map) output boolean in Python, but truthy map object in IPython
问题
I'm using python 3.10.1, interactively through ipython (7.31.0, calling the same python 3.10.1) for exploration, and then directly through python once my scripts are ready.
I had a bug in my code which I reduced to the following difference in behavior between the two:
[IPython]
In [1]: any(map(bool, ("")))
Out[1]: <map at 0x7f7f2d6061d0>
[CPython]
>>> any(map(bool, ("")))
False
Because the output map
object in IPython is truthy, when using the code in an if
statement the two programs will give opposite results. I'd like to know what's causing this difference, if there is anything I can do to fix it, and if there are other bugs (features?) like it that I should be aware of.
英文:
I'm using python 3.10.1, interactively through ipython (7.31.0, calling the same python 3.10.1) for exploration, and then directly through python once my scripts are ready.
I had a bug in my code which I reduced to the following difference in behavior between the two:
[IPython]
In [1]: any(map(bool, ("")))
Out[1]: <map at 0x7f7f2d6061d0>
[CPython]
>>> any(map(bool, ("")))
False
Because the output map
object in IPython is truthy, when using the code in an if
statement the two programs will give opposite results. I'd like to know what's causing this difference, if there is anything I can do to fix it, and if there are other bugs (features?) like it that I should be aware of.
答案1
得分: 5
检查 any.__module__
。它应该显示为 'builtins'
。如果不是这样,那么执行 del any
。
这个症状通常意味着您已经用与numpy相同名称的函数遮蔽了内置的 any
:
>>> any(map(bool, ("")))
False
>>> from numpy import any
>>> any(map(bool, ("")))
<map object at 0x7ffff6874a90>
IPython会这样做 如果您在 --pylab
模式下启动它,或者使用 %pylab
魔法启用了它。
英文:
Check any.__module__
. It should say 'builtins'
. If it doesn't, then execute del any
.
This symptom usually means you have shadowed the built-in any
with numpy's function of the same name:
>>> any(map(bool, ("")))
False
>>> from numpy import any
>>> any(map(bool, ("")))
<map object at 0x7ffff6874a90>
IPython will do this if you've started it in --pylab
mode, or enabled that with the %pylab
magic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论