- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用抽象基类来编写 Python 的类型注释来编写一些接口(interface)。有没有办法注释 *args
和 **kwargs
的可能类型?
例如,如何表示函数的合理参数是一个 int
或两个 int
? type(args)
给出 Tuple
所以我的猜测是将类型注释为 Union[Tuple[int, int], Tuple[int]]
,但这不起作用。
from typing import Union, Tuple
def foo(*args: Union[Tuple[int, int], Tuple[int]]):
try:
i, j = args
return i + j
except ValueError:
assert len(args) == 1
i = args[0]
return i
# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))
来自 mypy 的错误消息:
t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
mypy 不喜欢这个函数调用是有道理的,因为它希望调用本身有一个 tuple
。解压后的加法也出现了我看不懂的打字错误。
如何注释 *args
和 **kwargs
的合理类型?
最佳答案
对于可变位置参数 (*args
) 和可变关键字参数 (**kw
),您只需为 one 这样的论点。
来自 Arbitrary argument lists and default argument values section 类型提示 PEP:
Arbitrary argument lists can as well be type annotated, so that the definition:
def foo(*args: str, **kwds: int): ...
is acceptable and it means that, e.g., all of the following represent function calls with valid types of arguments:
foo('a', 'b', 'c')
foo(x=1, y=2)
foo('', z=0)
所以你想像这样指定你的方法:
def foo(*args: int):
但是,如果您的函数只能接受一个或两个整数值,则根本不应该使用 *args
,而是使用一个显式位置参数和第二个关键字参数:
def foo(first: int, second: Optional[int] = None):
现在您的函数实际上仅限于一个或两个参数,并且如果指定,则两者都必须是整数。 *args
always 表示 0 或更多,并且不能被类型提示限制到更具体的范围。
关于python - *args 和 **kwargs 的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37031928/
我有一个像 s = "title='bah' name='john and jill' purple='haze' none=None i=1" 我正在寻找一种将其放入字典的 Pythonic 方式(
我正在通过教程阅读有关模板 View 的内容,其中一些代码让我感到困惑。作者使用了这个代码示例 from django.utils.timezone import now class AboutUsV
看不懂下面的例子,假设我有这些功能: # python likes def save(filename, data, **kwargs): fo = openX(filename, "w",
假设我们有一个像这样的函数声明 def myfunc(a=None,b=None): as_dict = {"a": a, "b": b,
def a(**akwargs): def b(bkwargs=akwargs): # how to not only use akwargs defaultly,but al
阅读 Python 文档,有几种创建字典的方法。 dict() dict(**kwargs) dict(mapping, **kwargs) dict(iterable, **kwargs) http
两种方法我都见过,但我不明白它们的区别以及我应该将什么作为“最佳实践”: def custom_function(**kwargs): foo = kwargs.pop('foo')
关闭。这个问题需要details or clarity .它目前不接受答案。 想改进这个问题吗? 通过 editing this post 添加细节并澄清问题. 关闭 8 年前。 Improve t
我需要将 args 和 kwargs 都存储在一个元组中以便稍后调用,那么在这种情况下元组中的适当值是 *args 还是 args?换句话说,这行得通吗: def __init__(self, *ar
我有这个查询 Location.objects.filter(locations_rate__rate=search_rate).distinct('id') 如何将 distinct() 设置为 *
是否可以简化 kwargs 选项的 bool 检查? 例如在 foo 中我必须检查很多选项: def foo(*args, **kwargs): if 'foo' in kwargs and k
我尝试运行 Python Data Science Essential 一书中的一个示例。但是,当我运行它时出现错误。实际上,我才刚刚开始学习 python。所以,我觉得很难修复这些错误。请帮我。这是
我正在尝试使用以下代码在一个大图中创建多个seaborn regplot: %matplotlib notebook import seaborn as sns from itertools impo
我有一个这样的函数:。如果有参数x,则它一定是布尔值。任何其他命名参数必须为int。。其他人将编写调用foo的函数,我希望他们能够传递x和kwargs。目前,这意味着调用foo()的每个函数除了kwa
当一个类继承自单个类时,调用父方法的首选方式是什么?我知道有两种调用父方法的方法。 选项 1: ParentClass.method(self, *args, **kwargs) 选项 2: supe
问题 我在 Dusty Phillips 的 Object Oriented Programming(为简洁起见而简化)中遇到了这段代码,但我不确定这个定义的特定部分。 class A: de
在创建数据类对象时我可以使用 kwargs 没有问题: @dataclass() class Data: name: str = 'Unnamed' additiona
在创建数据类对象时我可以使用 kwargs 没有问题: @dataclass() class Data: name: str = 'Unnamed' additiona
我在下面运行了一个装饰器演示。 def logger(func): def inner(*args, **kwargs): print(args) print(
如何使用“一个”类参数**kwargs设置对象属性? 我想要的是在一个循环中执行此代码: class purchase(): def __init__(self,**kwargs):
我是一名优秀的程序员,十分优秀!