[英]Is there a way to use a dataclass, with fields with defaults, with __slots__
I would like to put __slots__
on a dataclass with fields with defaults. 我想将__slots__
放在带有默认字段的数据类上。 When I try do that, I get this error: 当我尝试这样做时,我收到此错误:
>>> @dataclass
... class C:
... __slots__ = ('x', 'y', )
... x: int
... y: int = 1
...
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: 'y' in __slots__ conflicts with class variable
Is there a way to achieve this? 有没有办法实现这个目标?
There is, by using the @add_slots decorator by ericvsmith : 通过使用ericvsmith的@add_slots装饰器 :
import dataclasses
def add_slots(cls):
# Need to create a new class, since we can't set __slots__
# after a class has been created.
# Make sure __slots__ isn't already set.
if '__slots__' in cls.__dict__:
raise TypeError(f'{cls.__name__} already specifies __slots__')
# Create a new dict for our new class.
cls_dict = dict(cls.__dict__)
field_names = tuple(f.name for f in dataclasses.fields(cls))
cls_dict['__slots__'] = field_names
for field_name in field_names:
# Remove our attributes, if present. They'll still be
# available in _MARKER.
cls_dict.pop(field_name, None)
# Remove __dict__ itself.
cls_dict.pop('__dict__', None)
# And finally create the class.
qualname = getattr(cls, '__qualname__', None)
cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
if qualname is not None:
cls.__qualname__ = qualname
return cls
>>> @add_slots
... @dataclass
... class C:
... __slots__ = ('x', 'y', )
... x: int
... y: int = 1
Adding __slots__
manually works as long as there are no defaults . 只要没有默认值,手动添加__slots__
就可以了 。 You can find related the Github issue here 你可以在这里找到相关的Github问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.