[英]Accept either int or tuple of ints as a python function parameter
I have the following function: 我有以下功能:
def port_status(self, port=(1, 2)):
for i in port:
print_status(i)
But I'd like the user to be able to also call the function with a single port number like so: 但我希望用户也可以使用单个端口号调用该函数,如下所示:
port_status(port=2)
In this specific case, it would end up as the following: 在这种特定情况下,最终结果如下:
TypeError: 'int' object is not iterable
Is there some python magic I could use here? 我在这里可以使用一些Python魔术吗?
You can check the type of port
. 您可以检查
port
的类型。
def port_status(self, port=(1, 2)):
if isinstance(port, int):
port = (port,)
for i in port:
print_status(i)
There's no magic, but in general you live with duck typing by trying to figure out if the input behaves in your expected way. 没有魔术,但是总的来说,您会通过尝试弄清楚输入是否以预期的方式工作来进行鸭子输入。 This can be coupled with trying to preprocess them first in the way you want.
这可以与尝试首先以所需方式对其进行预处理相结合。
For example, you can modify your function to look like: 例如,您可以将函数修改为如下所示:
def port_status(self, port)
ports = validate_ports(port)
for p in ports:
# use p as individual port
where, in the function validate_ports
you can use a try
block to tentatively figure out (and possibly bridge) the desired behavior and the actual one, for a very crude example: 其中,在一个
validate_ports
函数中,您可以使用一个try
块来尝试找出(并可能桥接)所需的行为和实际的行为,例如一个非常粗糙的示例:
def validate_ports(port):
try:
portiter = iter(port)
except TypeError:
return [port]
return list(portiter)
This function always returns a list, so in the case when the input is a valid list of int
s or an int
, nothing breaks. 此函数始终返回一个列表,因此,当输入是
int
或int
的有效列表时,不会中断任何内容。 But despite the name, the individual members can still behave badly, and you'll need to handle exceptions in the rest of the code. 但是,尽管有名称,但单个成员仍然可能表现不佳,并且您需要在其余代码中处理异常。
In general, using isinstance
can be unwieldy with Python's duck typing, and concepts like "a sequence of int
s" isn't really enforceable in Python. 通常,在Python的鸭子类型上使用
isinstance
可能很笨拙 ,并且“ int
的序列”之类的概念在Python中实际上不是可强制执行的。 It's your choice to mix some LBYL with EAFP or go purist, and the choice is quite subjective, which might as well be described as "magic". 您可以将一些LBYL与EAFP混合使用,也可以选择纯粹,这是非常主观的选择,也可以称为“魔术”。
Your for i in port requires port to be a iterable object. 您的for in in要求port是一个可迭代的对象。 So you could just pass port_status port=(2), and it would work.
因此,您只需传递port_status port =(2),它就可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.