简体   繁体   中英

Different behavior on `functools.partial`

Why get_score would cause such Error but fx don't

from operator import getitem
from functools import partial
# getitem(a, b) -- Same as a[b]

d = dict(name='foo', score=100)
get_score = partial(getitem, b='score')
get_score(d)
# expect 100 but 
# TypeError: getitem() takes no keyword arguments

def f(x, y):
    return x+y
fx = partial(f, y=2)
fx(5) == 7 # True

getitem() is probably implemented in C and not Python, and does not support keyword arguments. Implementation of Python functions using the C API is considerably different to implementation using Python itself. In particular the argument parsing is more explicit when using the C API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM