【问题标题】:using metaclass for default attribute init使用元类进行默认属性初始化
【发布时间】:2020-12-08 02:11:37
【问题描述】:

假设我有一个看起来像这样的资源类:

class Resource(metaclass=ResourceInit):
    def __init__(self, a, b):
        self.a = a
        self.b = b

我的目标是创建一个元类,即ResourceInit,它可以自动将属性分配给实例化的Resource

我的以下代码不起作用:

config = {"resources": {"some_resource": {"a": "testA", "b": "testB"}}}

class ResourceInit(type):

    def __call__(self, *args, **kwargs):

        obj = super(ResourceInit, self)

        argspec = inspect.getargspec(obj.__self__.__init__)

        defaults = {}

        for argument in [x for x in argspec.args if x != "self"]:
            for settings in config["resources"].values():
                for key, val in settings.items():
                    if key == argument:
                        defaults.update({argument: val})
            if os.environ.get(argument):
                defaults.update({argument: os.environ[argument]})

        defaults.update(kwargs)
        for key, val in defaults.items():
            setattr(obj, key, val)
        return obj

想法是,在实例化时使用这个元类

res = Resource()

如果config 中存在ab 或作为环境变量,将自动填充它..

显然这是一个虚拟示例,其中ab 将更加具体,即xx__resource__name

我的问题:

  1. 您能否将参数传递给子类中的元类,即resource="some_resource"
  2. 如果configos.environ 未设置,我怎样才能让它像任何普通类一样工作,即x = Test() 导致TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'

【问题讨论】:

  • 类方法比元类简单得多。
  • Resource 本身的__init__ 方法中直接将派生自config 或环境变量的值分配给ab 有什么问题?
  • @blhsing。我在想同样的事。这方面的一切都是不必要的复杂。
  • 最后一部分Test是什么x = Test()?
  • 这太复杂了,因为存在具有非常大配置的资源,我宁愿依靠不需要配置的人进行实例化,除非它们不存在。@MadPhysicist 我的意思是x = Resource()

标签: python init metaclass


【解决方案1】:

替代方案

你让这变得比它需要的更复杂。简单的解决方案如下所示:

def get_configured(name, value, config):
    if value is None:
        try:
            value = next(c for c in config['resources'].values() if name in c)[name]
        except StopIteration:
            value = os.environ.get(name, None)
    return value

class Resource:
    def __init__(self, a=None, b=None):
        self.a = get_configured('a', a, config)
        self.b = get_configured('a', b, config)

该函数是可重用的,您可以轻松地对其进行修改,以最大限度地减少每个类的样板数量。

完整答案

但是,如果您确实坚持走元类之路,您也可以将其简化。您可以在类定义中添加任意数量的仅关键字参数(问题 1)。

class Resource(metaclass=ResourceInit, config=config): ...

config,以及除metaclass 之外的任何其他参数将直接传递给元元类的__call__ 方法。从那里,它们被传递给元类中的__new____init__。因此,您必须实现__new__。您可能想改为实现__init__,但是如果您传入关键字参数,则从type.__new__ 调用的object.__init_subclass__ 会引发错误:

class ResourceInit(type):
    def __new__(meta, name, bases, namespace, *, config, **kwargs):
        cls = super().__new__(meta, name, bases, namespace, **kwargs)

注意最后一个参数configkwargs。位置参数作为bases 传递。 kwargs 在传递给 type.__new__ 之前不得包含意外参数,但应传递您班级中 __init_subclass__ 所期望的任何内容。

当您可以直接访问namespace 时,无需使用__self__。请记住,这只会在您的 __init__ 方法被实际定义时更新默认值。你可能不想惹父母__init__。为安全起见,如果__init__ 不存在,我们将引发错误:

        if '__init__' not in namespace or not callable(getattr(cls, '__init__')):
            raise ValueError(f'Class {name} must specify its own __init__ function')
        init = getattr(cls, '__init__')

现在我们可以使用类似于我上面显示的函数来建立默认值。您必须小心避免以错误的顺序设置默认值。因此,虽然所有仅关键字参数都可以具有可选的默认值,但只有列表末尾的位置参数才能获得它们。这意味着位置默认值的循环应该从末尾开始,并且一旦找到没有默认值的名称就应该立即停止:

def lookup(name, configuration):
    try:
        return next(c for c in configuration['resources'].values() if name in c)[name]
    except StopIteration:
        return os.environ.get(name)

...

        spec = inspect.getfullargspec(init)

        defaults = []
        for name in spec.args[:0:-1]:
            value = lookup(name, config)
            if value is None:
                break
            defaults.append(value)

        kwdefaults = {}
        for name in spec.kwonlyargs:
            value = lookup(name, config)
            if value is not None:
                kwdefaults[name] = value

表达式spec.args[:0:-1] 向后迭代除第一个以外的所有位置参数。请记住,self 是一个传统的而非强制性的名称。因此,按索引删除它比按名称删除它更可靠。

使defaultskwdefaults 值有意义的关键是将它们分配给实际__init__ 函数对象上的__defaults____kwdefaults__问题2) :

        init.__defaults__ = tuple(defaults[::-1])
        init.__kwdefaults__ = kwdefaults
        return cls

__defaults__ 必须反转并转换为元组。前者对于获得正确的论点顺序是必要的。 __defaults__ 描述符需要后者。

快速测试

>>> configR = {"resources": {"some_resource": {"a": "testA", "b": "testB"}}}
>>> class Resource(metaclass=ResourceInit, config=configR):
...     def __init__(self, a, b):
...         self.a = a
...         self.b = b
... 
>>> r = Resource()
>>> r.a
'testA'
>>> r.b
'testB'

TL;DR

def lookup(name, configuration):
    try:
        return next(c for c in configuration['resources'].values() if name in c)[name]
    except StopIteration:
        return os.environ.get(name)

class ResourceInit(type):
    def __new__(meta, name, bases, namespace, **kwargs):
        config = kwargs.pop('config')
        cls = super().__new__(meta, name, bases, namespace, **kwargs)

        if '__init__' not in namespace or not callable(getattr(cls, '__init__')):
            raise ValueError(f'Class {name} must specify its own __init__ function')
        init = getattr(cls, '__init__')
        spec = inspect.getfullargspec(init)

        defaults = []
        for name in spec.args[:0:-1]:
            value = lookup(name, config)
            if value is None:
                break
            defaults.append(value)

        kwdefaults = {}
        for name in spec.kwonlyargs:
            value = lookup(name, config)
            if value is not None:
                kwdefaults[name] = value

        init.__defaults__ = tuple(defaults[::-1])
        init.__kwdefaults__ = kwdefaults

        return cls

【讨论】:

  • 这太棒了......关于如何扩展这样的东西的一个问题:假设我们有一个 class Resource 接受 a, b, c 参数......元类将能够通过配置找到a, b,而不是c。目前使用这个,如果存在额外的c 参数,则会出现错误:TypeError: __init__() missing 3 required positional arguments: 'a', 'b', and 'c',我希望它只丢失c。这可能吗?
  • @sgerbhctim。这就是问题所在。在具有默认值的参数之后,您不能有一个没有默认值的参数。因此,无论找到什么,您都可以为c 分配一些默认值,或者重新排列参数列表(这非常糟糕)。
猜你喜欢
  • 1970-01-01
  • 2012-03-02
  • 2023-03-11
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
相关资源
最近更新 更多