替代方案
你让这变得比它需要的更复杂。简单的解决方案如下所示:
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)
注意最后一个参数config 和kwargs。位置参数作为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 是一个传统的而非强制性的名称。因此,按索引删除它比按名称删除它更可靠。
使defaults 和kwdefaults 值有意义的关键是将它们分配给实际__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