【发布时间】:2021-06-10 08:15:43
【问题描述】:
在 Python 3.8.8 中,我正在寻找一种方法来保存和调用一系列函数和相关参数。我遇到了看起来像这样做的好方法的数据类,但无法检索函数名称或参数。我什至不确定数据类是否可以实现我想要做的事情。
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 包含预期值。
name,fn,args
step 1,<function foo at 0x0000019E3A12EE50>,"('bar 1',)"
step 2,<function foo at 0x0000019E3A12EE50>,"('bar 2',)"
但当回读时,rsteps 会以布尔值结束 fn 和 arg。
[Step(name='step 1', fn=True, args=True), Step(name='step 2', fn=True, args=True)]
我将fn 和arg 类型定义为any,因为我找不到任何可以在那里工作的类型。我试过Callable[...,bool] (from typing import Callable) 但得到了一个TypeError: 'type' object is not subscriptable。
【问题讨论】:
标签: python python-3.x csv