由于**kwargs
,我有一个函数接受一个奇怪的参数
def create_record_table(Base, table_name, **kwargs):
class RecordTable(Base):
__tablename__ = table_name
id = Column(Integer, primary_key=True)
for key, value in kwargs.items():
exec("{0} = {1}".format(key,value))
return RecordTable
这是有人调用此函数的示例
test = create_record_table(Base, "testtable", index="Column(String)")
我想创建一个函数或类来创建或返回index="Column(String)"
部分。
例如,用户可以这样做
index = Atomic("col_name", "String")
test = create_record_table(Base, "testtable", index)
或类似的:
index = Atomic("col_name", "Integer")
test = create_record_table(Base, "testtable", index)
怎么样:
def Atomic(col_name, col_type):
return {'index': '%s(%s)' % (col_name, col_type)}
然后你需要像这样调用create_record_table
:
kwargs = Atomic('testcol', 'String')
create_record_table(Base, 'testtable', **kwargs)
如果你不想在调用**
时在kwargs
之前添加create_record_table
,你可以将create_record_table
的声明更改为:
def create_record_table(Base, table_name, kwargs):
现在,您可以像这样调用它:
kwargs = Atomic('testcol', 'String')
create_record_table(Base, 'testtable', kwargs)
但通过这种方式,它将使create_record_table
与旧代码不兼容。