Search code examples
pythonpartialfunctools

Python: functools.partial returns error


I am encountering a problem using functools.partial.

My code:

selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate']

def awsome_count(x,i):
    if selected_words[i] in x:
        y=1
    else:
        y=0
    return y

partialfun=functools.partial(awsome_count,0)

partialfun(products[2]['word_count'])

products is a SFrame.

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-108-e51348a5d1f0> in <module>()
----> 1 partialfun(products[2]['word_count'])

<ipython-input-66-9ba8c7128add> in awsome_count(x, i)
      1 def awsome_count(x,i):
----> 2     if selected_words[i] in x:
      3         y=1
      4     else:
      5         y=0

TypeError: list indices must be integers, not dict

I am using partial function, is because I want to use apply function:

products['word_count'].apply(functools.partial(awsome_count,0)

Solution

  • You gave your partial() object one positional argument:

    functools.partial(awsome_count, 0)
    

    That argument is applied first; additional positional arguments are added to that one, so your call:

    partialfun(products[2]['word_count'])
    

    becomes:

    awesome_count(0, products[2]['word_count'])
    

    which is the wrong order for your function.

    If you want to apply a default value for the i argument of your function, use a keyword argument instead of a positional argument:

    partialfun = functools.partial(awsome_count, i=0)
    

    Now the call partialfun(products[2]['word_count']) becomes

    awsome_count(products[2]['word_count'], i=0)