只有在必要時,Python是否可以將某個條件的參數作爲參數傳遞給函數?例如:一個完整的,如果條件: Python函數 - 傳遞一個完整的if條件作爲參數
# /!\ checking if customer_name is NULL (NOT NULL field in destination database)
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
我工作的一個腳本,從MySQL到PostgreSQL自動化數據遷移。一些表在兩個數據庫(源和目標)中具有相同的結構,其他表在結構上不同,而其他表僅具有數據類型差異。
我想了解是否有可能在功能內部「注入」一個條件,以便爲上述段落中提到的所有3種情況使用相同的代碼段每次都會有所不同。
下面是一個例子(代碼段我們正在調查注入的可能性是黃 - >把它作爲一個參數):
def migrate_table(select_query, insert_query, tmp_args):
# Cursors initialization
cur_psql = cnx_psql.cursor()
cur_msql.execute(select_query)
args = []
for row in cur_msql:
# /!\ checking if customer_name is NULL (NOT NULL field in destination database)
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
args.append(cur_psql.mogrify(tmp_args, row))
args_str = ','.join(args)
if len(args_str) > 0:
try:
cur_psql.execute(insert_query + args_str)
except psycopg2.Error as e:
print "Cannot execute that query", e.pgerror
sys.exit("Leaving early this lucky script")
## Closing cursors
cur_psql.close()
實際上我把我的功能是這樣的:
migrate_compatable(
"SELECT customer_id, customer_name, contact_name, address, city, postal_code, country FROM mysqlcustomers",
"INSERT INTO psqlcustomers (customer_id, customer_name, contact_name, address, city, postal_code, country"
"(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)"
)
我想知道,如果是的東西可以添加充分利用在輸入一個完整的狀態參數
目前還不清楚你想要問什麼,但你可能會傳遞一個函數/ lambda來做你想做的事情。 – jonrsharpe