是否可以从operator.methodcaller获取函数名称?

时间:2012-08-27 11:36:46

标签: python

是否可以从Python中的operator.methodcaller获取函数名称?

import operator as op
mc = op.methodcaller('foo')
print magic(mc) #should print 'foo'

如何使magic获取方法调用方法的名称?

1 个答案:

答案 0 :(得分:4)

确实如此,但您需要深入了解C内部(不是推荐的解决方案):

from ctypes import *

PyObject_HEAD = [
    ("ob_refcnt", c_size_t),
    ("ob_type", c_void_p),
]

class methodcallerobject(Structure):
    _fields_ = PyObject_HEAD + [
        ("name", c_void_p),
        ("args", c_void_p),
        ("kwds", c_void_p),
    ]

def magic(methcallobj):
    if not isinstance(methcallobj, operator.methodcaller):
        raise TypeError("not a methodcaller")

    c_methcallobj = cast(c_void_p(id(methcallobj)), POINTER(methodcallerobject)).contents

    return cast(c_methcallobj.name, py_object).value

请注意,这仅适用于CPython,并不是特别漂亮。但如果这是唯一可用的解决方案,那就更好了。