Skip to content

Commit bec9644

Browse files
committed
restore dataclass_extensions. See #345
1 parent a1db174 commit bec9644

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import dataclasses
2+
#
3+
# The dataclass library builds a rigid `__init__` function that doesn't allow any unrecognized named parameters
4+
#
5+
# The purpose of this extension is to enhance the library to allow additional keyword arguments to passed in
6+
# and then on to the __post_init__ function that can deal with them accordingly
7+
8+
# Beware that there is no promise that signature of the create function will remain consistent
9+
loc_fn = dataclasses._create_fn
10+
11+
12+
def dc_create_fn(name, args, body, *_posargs, **_kwargs):
13+
# If overriding the initializer and using a post init
14+
if name == '__init__' and dataclasses._POST_INIT_NAME in body[-1]:
15+
# Then insert the kwargs into the both the call and the post init
16+
pi_parms = body[-1].rsplit(')', 1)[0]
17+
body[-1] = pi_parms + ('' if pi_parms[-1] == '(' else ',') + ' **_kwargs)'
18+
return loc_fn(name, list(args) + ["**_kwargs"], body, *_posargs, **_kwargs)
19+
else:
20+
return loc_fn(name, args, body, *_posargs, **_kwargs)
21+
22+
23+
dataclasses._create_fn = dc_create_fn
24+
25+
# The following line is here solely to be backwards compatible.
26+
dataclasses_init_fn_with_kwargs = dataclasses._init_fn
27+
28+
# The following line can be used to make certain that the import of the new create function doesn't get
29+
# discarded as being potentially unused
30+
DC_CREATE_FN = True

0 commit comments

Comments
 (0)