In Python 3.8.8, I am looking for a way to save and recall a sequence of functions and associated arguments. I came across dataclasses which looks like a good way of doing this, but can't retrieve the function names or arguments. I'm not even sure if what I want to do is possible with dataclasses.
from dataclasses import dataclass
from dataclass_csv import DataclassWriter, DataclassReader
def foo(bar):
print(bar)
return True
@dataclass
class Step:
name: str
fn: any
args: any = None
steps = [ Step(name ='step 1', fn=foo, args=('bar 1',)),
Step(name ='step 2', fn=foo, args=('bar 2',)) ]
with open('steps.csv', "w") as f:
w = DataclassWriter(f, steps, Step)
w.write()
with open("steps.csv") as f:
reader = DataclassReader(f, Step)
rsteps = [row for row in reader]
print(rsteps)
steps.csv contains expected values.
name,fn,args
step 1,<function foo at 0x0000019E3A12EE50>,"('bar 1',)"
step 2,<function foo at 0x0000019E3A12EE50>,"('bar 2',)"
But when read back, rsteps
ends up with booleans for fn
and arg
.
[Step(name='step 1', fn=True, args=True), Step(name='step 2', fn=True, args=True)]
I defined the fn
and arg
types as any
because I couldn't find any type that would work there. I tried Callable[...,bool]
(from typing import Callable
) but got a TypeError: 'type' object is not subscriptable.