从装饰类方法中检索导入字符串

Retrieve Import string from a decorated classmethod

我正在尝试在修饰的 @classmethod 中检索导入字符串,以便在管道系统中注册该字符串。但是当我检查装饰器函数中的函数对象时,找不到有关 class 对象或 class 名称的任何信息。

所以代码看起来像这样:

def import_string_decorator(**opt_kwargs):

    def wrap(f):

        # Here is the problem
        if inspect.ismethod(f):
            class_name = f.im_self.__name__
            import_string = f.__module__ + "." class_name + "." + f.__name__
            # But this doesn't work because f no longer is a <bound method to class 'SomeClass'> but is a regular <function>
        else:
            import_string = f.__module__ + "." + f.__name__

        # Register the string
        do_something(import_string, **opt_kwargs)

        def wrapped_f(*args, **kwargs):

            f(*args, **kwargs)

        return wrapped_f

    return wrap


# Decorated Class
opt_dict = {"some": "values"}

class SomeClass(object):

    @classmethod
    @import_string_decorator(**opt_dict)
    def double_decorated_function(cls, *args, **kwargs):

        pass

但我还没有找到一种方法来检索装饰函数的 class 对象。 inspect.ismethod() 函数也 returns False 因为它检查下面的 isinstance(types.MethodType)

函数装饰器做不到你想要的。在构建 class 对象 之前创建并修饰函数对象 。 Python 首先执行 class 主体,然后生成的名称形成 class 属性。

当您使用 descriptor protocol.

访问作为属性的名称时,方法的绑定将动态发生。

您需要连接到 class 创建才能访问 class 名称;您可以使用 class 装饰器,或使用元 class。如果这样更容易,您可以将这些技术与函数装饰器结合起来:

@registered_class
class SomeClass(object):

    @classmethod
    @import_string_decorator(**opt_dict)
    def double_decorated_function(cls, *args, **kwargs):
        pass

其中 import_string_decorator 可以注释函数(例如,您可以在其上设置一个属性)以便 registered_class 装饰器在装饰 class 时进行检查。