Closed MartinThoma closed 3 years ago
$ astpretty --no-show-offsets /dev/stdin <<< `cat example.txt`
[...]
ClassDef(
name='Person',
bases=[],
keywords=[],
body=[
FunctionDef(
name='__init__',
args=arguments(
posonlyargs=[],
args=[
arg(arg='self', annotation=None, type_comment=None),
arg(arg='first_name', annotation=None, type_comment=None),
arg(arg='last_name', annotation=None, type_comment=None),
arg(arg='birthdate', annotation=None, type_comment=None),
],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[],
),
body=[
Assign(
targets=[
Attribute(
value=Name(id='self', ctx=Load()),
attr='first_name',
ctx=Store(),
),
],
value=Name(id='first_name', ctx=Load()),
type_comment=None,
),
Assign(
targets=[
Attribute(
value=Name(id='self', ctx=Load()),
attr='last_name',
ctx=Store(),
),
],
value=Name(id='last_name', ctx=Load()),
type_comment=None,
),
Assign(
targets=[
Attribute(
value=Name(id='self', ctx=Load()),
attr='birthdate',
ctx=Store(),
),
],
value=Name(id='birthdate', ctx=Load()),
type_comment=None,
),
],
decorator_list=[],
returns=None,
type_comment=None,
),
],
decorator_list=[],
)
And the dataclass:
$ astpretty --no-show-offsets /dev/stdin <<< `cat example.txt`
ClassDef(
name='Person',
bases=[],
keywords=[],
body=[
AnnAssign(
target=Name(id='first_name', ctx=Store()),
annotation=Name(id='str', ctx=Load()),
value=None,
simple=1,
),
AnnAssign(
target=Name(id='last_name', ctx=Store()),
annotation=Name(id='str', ctx=Load()),
value=None,
simple=1,
),
AnnAssign(
target=Name(id='birthdate', ctx=Store()),
annotation=Name(id='date', ctx=Load()),
value=None,
simple=1,
),
],
decorator_list=[Name(id='dataclass', ctx=Load())],
)
Explanation
Dataclasses were introduced with PEP 557. Data Classes can be thought of as "mutable namedtuples with defaults".
Dataclasses should be used when the primary focus is to store data.
Dataclasses help, because they have a good
__str__
and__eq__
implementation and you don't have to write__init__
.Example
As an example why dataclasses are nice:
gives: