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

les*_*ese 2 python parameters if-statement function

在 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']
Run Code Online (Sandbox Code Playgroud)

我正在编写一个脚本,它将自动将数据从 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()
Run Code Online (Sandbox Code Playgroud)

实际上我是这样调用我的函数的:

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)"
)
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以添加一个参数来输入完整条件

mgu*_*arr 5

正如@jonrsharpe 所建议的,您可以修改您的migrate_table函数以传递您将使用以下命令调用的检查函数row

def check_customer_name(row):
    if row['customer_name'] == NULL:
        row['customer_name'] = row['contact_name']
    return row
Run Code Online (Sandbox Code Playgroud)

然后在migrate_table

def migrate_table(..., check_function = None):
    ...
    if callable(check_function):
        row = check_function(row)
    ...
Run Code Online (Sandbox Code Playgroud)

你的电话会变成:

migrate_table("...long sql query...", "...", check_customer_name)
Run Code Online (Sandbox Code Playgroud)

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