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

时间:2015-10-19 13:06:58

标签: python function if-statement parameters

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)"
)

我想知道如果有可能添加一个输入完整条件的参数

1 个答案:

答案 0 :(得分:2)

根据@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)

您可以根据需要创建任意数量的检查功能。