pythonnumpyipythonanyshadowing

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.


Solution

  • 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.