我需要多次运行一个函数,每次5个参数中有3个保持相同。我该如何编写一个仅将唯一参数作为输入并将内部函数的输出作为唯一变量返回的函数?
我要运行的功能是SQLalchemy的一部分:
sales = Table('sales', metadata, autoload=True, autoload_with=engine, schema=None)
第一个参数,表名,总是不同的,也应该是变量名。最后一个参数有时会有所不同。
我的想法是创建一个带有table_name的字典:schema_name并将其传递给遍历字典并运行Table函数的函数。
table_names = {'sales': None, 'orders': None, 'customers': 'cust_data'}
def represent_tables(tables: dict):
for table, schema in tables:
nonlocal exec(table)
exec(table) = Table(table, metadata, autoload=True,
autoload_with=engine, schema=schema)
represent_tables(table_names)
我想这里有两个问题。首先,如何使用另一个变量中包含的字符串来命名新变量?其次,如何从函数中返回变量,以便以后可以调用它?
答案 0 :(得分:1)
您通常不想动态创建变量。改用像字典这样的数据结构。
如何编写仅将唯一参数作为输入并将内部函数的输出作为唯一变量返回的函数?
您可以创建一个函数,该函数从当前作用域中提取所需的对象,并仅返回一个Table
实例:
engine = create_engine(...)
metadata = MetaData()
def create_table(name, schema=None):
return Table(name, metadata, autoload=True, autoload_with=engine, schema=schema)
然后您可以创建一个表字典:
tables = {
'sales': create_table('sales'),
'orders': create_table('orders'),
'customers': create_table('customers', schema='cust_data'),
}
如果您希望以减少可读性为代价减少重复,则可以使用字典理解从描述表的对象创建表:
table_schemas = {
'sales': None,
'orders': None,
'customers': 'cust_data',
}
tables = {
name: create_table(name, schema)
for name, schema in table_schemas.items()
}
SQLAlchemy也有一个可能有用的Metadata.reflect()
method。