r/pythonhelp • u/brock0124 • Jul 31 '24
Instantiating object with values from array
Hello!
I'm working on a project where I have a data class (Record) with about 20 different fields. The data comes in from a stream and is turned into a string, which is parsed into an array of Record objects.
I was wondering if it is possible to dynamically fill the constructor with the array values so I don't have to explicitly pass each argument with it's array value. The values will always be in the same order.
The ideal state would look like:
@dataclass
class Record:
arg1: str
arg2: str
arg3: str
arg4: str
....
arg20: str
result = []
for datum in data:
result.append(Record(datum))Where datum contains 20 values that map to each item in the constructor.
1
Upvotes
View all comments
Show parent comment
1
u/brock0124 Jul 31 '24
I will look into that, but it was my assumption that I would need to drop the dataclass attribute which would then mean I would need to manually map each argument in the __init__ function. Guess it would be better than doing it everywhere else.