Python函数 - 将完整的if条件作为参数传递

4

在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的数据迁移。一些表在两个数据库(源和目标)中具有相同的结构,而其他表则在结构上不同,还有一些仅具有数据类型差异。
我试图理解是否可能将条件“注入”到函数中,以便在所有上述段落中使用相同的代码片段。每次条件都会有所不同。
以下是一个示例(我正在调查注入的可能性的代码片段为黄色->将其作为参数传递):
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)"
)

我想知道是否有可能添加一个接受完整条件作为输入的参数


2
不清楚你想要问什么,但是你可以传递一个函数/lambda来做你想要的事情。 - jonrsharpe
1个回答

7

正如@jonrsharpe所建议的那样,您可以修改migrate_table函数,以传递一个检查函数,您将使用row调用该函数:

def check_customer_name(row):
    if row['customer_name'] == NULL:
        row['customer_name'] = row['contact_name']
    return row

接着在migrate_table中:

def migrate_table(..., check_function = None):
    ...
    if callable(check_function):
        row = check_function(row)
    ...

您的呼叫会变成:
migrate_table("...long sql query...", "...", check_customer_name)

您可以创建任意多的检查函数来测试您的条件。

完美且符合Python风格。 :) - Bálint Sass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接