from dataclasses import dataclass, is_dataclass
@dataclass
class Point:
x: int
y: int
@dataclass
class Empty:
pass
class Plain:
pass
assert is_dataclass(Point), 'decorated class is a dataclass'
assert is_dataclass(Empty), 'empty decorated class is a dataclass'
assert not is_dataclass(Plain), 'plain (undecorated) class is not a dataclass'
assert not is_dataclass(int), 'a builtin type is not a dataclass'
assert not is_dataclass(5), 'a non-class value is not a dataclass'
assert not is_dataclass('hi'), 'a string is not a dataclass'
e = Empty()
assert is_dataclass(e), 'an instance of a dataclass is itself a dataclass'
assert Point.__name__ == 'Point'
assert list(Point.__dataclass_fields__) == ['x', 'y']
assert list(Empty.__dataclass_fields__) == []
assert not hasattr(Plain, '__dataclass_fields__'), 'a plain class has no field mapping'
assert e.__dataclass_fields__ is Empty.__dataclass_fields__
@dataclass
class Defaulted:
a: int
b: str = 'hi'
b = Defaulted.__dataclass_fields__['b']
assert type(b).__name__ == 'Field'
assert b.name == 'b'
assert b.default == 'hi'
assert b.type in ('str', str)
assert b.init is True
assert b.repr is True
assert b.compare is True
assert b.kw_only is False
assert b.hash is None
if hasattr(b, 'doc'):
assert b.doc is None
try:
b.nope
assert False, 'expected AttributeError'
except AttributeError as exc:
assert str(exc) == "'Field' object has no attribute 'nope'"