1

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)
0

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, the answer definitely helpful. I voted up just now, not sure whether I incorrectly vote just now. Sorry about that.
No worries, it can't have been you as you can't downvote until you have 125 points or more. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.