Vor Python 3.14 konnte ich Folgendes tun:
Code: Select all
class C:
foo: int
bar: int
__slots__ = (*__annotations__,)
not_a_slot: ClassVar[str] = 'some class variable'
Code: Select all
@dataclass(slots=True)Gibt es eine 3.8-kompatible, aber zukunftssichere Möglichkeit, einen __slots__ zu erreichen, der auf einer Teilmenge annotierter Attribute basiert, aber ohne die Namen zu wiederholen?
Die einzige Problemumgehung, die ich habe Ich habe herausgefunden, dass ich einen Klassendekorator erstellen soll, der eine Klasse mit dem Satz __slots__ erstellt, also:
Code: Select all
from typing import ClassVar, get_origin
try:
from inspect import get_annotations
except ImportError:
def get_annotations(x):
return x.__annotations__
def annotations_to_slots(klass):
class Out(klass):
__slots__ = tuple(
name
for name, declared_type in get_annotations(klass).items()
if get_origin(declared_type) is not ClassVar
)
Out.__name__ = klass.__name__
try:
Out.__doc__ = klass.__doc__
except AttributeError:
pass
return Out
@annotations_to_slots
class C:
__slots__ = () # will be filled in by @annotations_to_slots
foo: int
bar: int
not_a_slot: ClassVar[str] = 'not a slot'
Gibt es einen besseren Ansatz?
Mobile version