用Python方式验证参数的方法是序列而不是字符串 [英] Pythonic way to verify parameter is a sequence but not string

查看:78
本文介绍了用Python方式验证参数的方法是序列而不是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数获取数据库表的列表作为参数,并返回要在这些表上执行的命令字符串,例如:

I have a function that gets a list of DB tables as parameter, and returns a command string to be executed on these tables, e.g.:

pg_dump( file='/tmp/dump.sql',
         tables=('stack', 'overflow'),
         port=5434
         name=europe)

应返回以下内容:

pg_dump -t stack -t overflow -f /tmp/dump.sql -p 5434 europe

这是通过tables_string='-t '+' -t '.join(tables)完成的.

从以下位置调用函数时,乐趣就开始了:tables=('stackoverflow')(字符串)而不是tables=('stackoverflow',)(元组),其结果是:

The fun begins when the function is called with: tables=('stackoverflow') (a string) instead of tables=('stackoverflow',) (a tuple), which yields:

pg_dump -t s -t t -t a -t c -t k -t o -t v -t e -t r -t f -t l -t o -t w
        -f /tmp/dump.sql -p 5434 europe

因为字符串本身正在被迭代.

Because the string itself is being iterated.

此问题建议在类型上使用断言,但是我不确定它是否足够Pythonic,因为它违反了鸭子类型约定.

This SO question suggests using asserts on the type, but I'm not sure it's Pythonic enough because it breaks the duck-type convention.

有什么见解吗?

亚当

推荐答案

在这种情况下,声明类型似乎是适当的-处理由于鸭子输入而看起来合法的常见滥用.

Asserting the type seems appropriate in this case - handling a common misuse that seems legal because of duck typing.

处理这种常见情况的另一种方法是测试字符串并作为特殊情况正确处理它.

Another way to handle this common case would be to test for string and handle it correctly as a special case.

最后,您可以鼓励将表名作为位置参数进行传递,这将减少这种情况的发生:

Finally, you could encourage passing the table names as positional parameters which would make this scenario less likely:

def pg_dump(*tables, **kwargs):
  file = kwargs['file']
  port = kwargs['port']
  name = kwargs['name']
  ...

pg_dump('stack', 'overflow', file='/tmp/dump.sql', port=5434, name='europe')

这篇关于用Python方式验证参数的方法是序列而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆