My solution, if anyone comes by here looking for one:
from dataclasses import _create_fn
def patched_create_fn(name: str, args: list[str], body: list[str], **kwargs):
if name == '__init__':
args.append('**kwargs')
if body == ['pass']:
body = []
body.append(f'{args[0]}.__extra_kwargs__ = kwargs')
return _create_fn(name, args, body, **kwargs)
Then you can either apply the patch at the top of a module where you declare
dataclasses and restore the original function at the bottom or you can
encapsulate the patching logic in a context manager and create your dataclasses
inside the scope of the contextmanager.
I tried the decorator route but it is not easy or clean. I either ended up
importing private stuff from the dataclasses module or duplicating entire code
code blocks just to ensure I didn't break stuff (e.g.: if a field has a
default_factory, for instance).
I don't think the dataclasses module is meant to be easily extended so this was
never going to result in clean code but this does the job with minimal hassle
and minimal importing of private stuff from the dataclasses module. I do wish
the dataclasses module could evolve a bit to either implement more options like
the one proposed initially or, even better, give an easier/clearer path for
users to customize the generation of dataclasses.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/ERBVUEIN2IH7SZAHTDLESL65HBWP5IFF/
Code of Conduct: http://python.org/psf/codeofconduct/