all(map) and any(map) output boolean in Python, but truthy map object in IPython

huangapple go评论69阅读模式
英文:

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, (&quot;&quot;)))
Out[1]: &lt;map at 0x7f7f2d6061d0&gt;

[CPython]

&gt;&gt;&gt; any(map(bool, (&quot;&quot;)))
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

&gt;&gt;&gt; any(map(bool, (&quot;&quot;)))
False
&gt;&gt;&gt; from numpy import any
&gt;&gt;&gt; any(map(bool, (&quot;&quot;)))
&lt;map object at 0x7ffff6874a90&gt;

IPython会这样做 如果您在 --pylab 模式下启动它,或者使用 %pylab 魔法启用了它。

英文:

Check any.__module__. It should say &#39;builtins&#39;. 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:

&gt;&gt;&gt; any(map(bool, (&quot;&quot;)))
False
&gt;&gt;&gt; from numpy import any
&gt;&gt;&gt; any(map(bool, (&quot;&quot;)))
&lt;map object at 0x7ffff6874a90&gt;

IPython will do this if you've started it in --pylab mode, or enabled that with the %pylab magic.

huangapple
  • 本文由 发表于 2023年3月4日 07:29:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定