Question

I want to check if any string elements in a list phrases contains certain keywords in a set phd_words. I want to use any but it doesn't work.

In[19]:
    import pandas as pd
    import psycopg2 as pg

    def test():
    phd_words = set(['doctor', 'phd'])
    phrases = ['master of science','mechanical engineering']
    for word in phrases:
        if any(keyword in word for keyword in phd_words):
            return 'bingo!'

test()

Out[20]: 
  bingo!

How should I fix this?

Was it helpful?

Solution

That may happen if you use IPython's %pylab magic:

In [1]: %pylab
Using matplotlib backend: Qt4Agg
Populating the interactive namespace from numpy and matplotlib

In [2]: if any('b' in w for w in ['a', 'c']):
   ...:     print('What?')
   ...:
What?

Here's why:

In [3]: any('b' in w for w in ['a', 'c'])
Out[3]: <generator object <genexpr> at 0x7f6756d1a948>

In [4]: any
Out[4]: <function numpy.core.fromnumeric.any>

any and all get shadowed with numpy functions, and those behave differently than the builtins. This is the reason I stopped using %pylab and started using %pylab --no-import-all so that it doesn't clobber the namespace like that.

To reach the builtin function when it is already shadowed, you can try __builtin__.any. The name __builtin__ seems to be available in IPython on both Python 2 and Python 3, which is probably on itself enabled by IPython. In a script, you would first have to import __builtin__ on Python 2 and import builtins on Python 3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top