[英]How can I use default arguments in a method with python-fire?
I am having an issue with python-fire
when a method has arguments with default values.当方法具有默认值 arguments 时,我遇到了python-fire
问题。 Consider the following code:考虑以下代码:
import fire
class SomeClass(object):
def __init__(self):
self.a = ''
self.b = ''
def methoda(self):
self.a = 'A'
return self
def methodb(self, x='B123'):
self.b = self.a + x
return self
def __str__(self):
return self.b
if __name__ == '__main__':
s = SomeClass()
s.methodb().methoda()
print(s.b) # this prints B123 correctly
fire.Fire(SomeClass)
As seen in the comments, in the print(sb), it is printing
B123` correctly.正如评论中所见,在print(sb), it is printing
了 B123`。 But when i change the order of the methods being called in fire from the command line, I am getting the odd behavior.但是当我从命令行更改被调用的方法的顺序时,我得到了奇怪的行为。
Example:例子:
> python x.py
B123 # correct
> python x.py methoda methodb
Here: B123
AB123 # both correct
> python x.py methodb --x B123 methoda
Here: B123
B123 # again both correct
> python x.py methodb methoda
Here: B123
methoda # this is not correct. It should print B123 here also
As you can see with the last example, if i call methodb
(which has an argument with a default value), it prints methoda
instead of B123
as expected.正如您在最后一个示例中看到的那样,如果我调用methodb
(它有一个带有默认值的参数),它会按预期打印methoda
而不是B123
。
My question is, How can I use a method that has a default argument value first in this type of scenario without passing in --x=something
?我的问题是,在这种情况下,如何在不传入--x=something
的情况下首先使用具有默认参数值的方法?
In short, how can i make > python x.py methodb methoda
properly print B123
?简而言之,我怎样才能使> python x.py methodb methoda
正确打印B123
?
You need to change def methodb(self, x='B123'):
to def methodb(self, *, x='B123'):
, which makes x
a keyword only argument, so it can no longer be used as a positional argument.您需要将def methodb(self, x='B123'):
更改为def methodb(self, *, x='B123'):
,这使x
成为仅关键字参数,因此它不能再用作位置争论。 This way fire will use the default value.这样火将使用默认值。
There has also been a github issue discussing this.还有一个github issue讨论这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.