简体   繁体   中英

How to pass Attributes to Custom Dataclass

I am currently trying to implement a self-written Dataclass wrapper/decorator in python. I have massive trouble passing the arguments and attributes of the function which i want to use that Decorator on.

My thoughtprocess until now: The decorator doesnt know how many attributes and argument the class has, but i somehow still have to access them. I then would have to access those via the " attribute " names. Since the dataclass decorator mainly does what the init does(and optionally eq and so on), i would have to pass the classes/instances dict to access all args. I have already tried to find it myself in Pythons Language reference in the Data Model, but i couldnt find it.

I would appreciate any kind of help, be it where i find the answer in the docs, some kind of tip or a little code snippet.

The dataclass decorator does essentially two steps while creating a default __init__ instance method for a class:

  1. It extracts all class variables using __annotations__ (See PEP 526 ) attribute of the class, as is documented in the docstring of dataclass .

  2. It creates a string containing the entire function definition, with a full parameter list, generated from the class variables of step 1 and if present their default values. It then uses exec to actually run that as python code, which in turn generates a new user-defined function object . That new object is finally assigned to the __init__ attribute of the decorated class object .

So to modify the parameter list of the newly created __init__ function to match the class variables, dataclass creates a new function definition. There seems to be no direct way of modifying the parameter list of a function object outside the function definition itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM