我想这两个问题是相关的,所以我将把它们放在一起:

1.- Is it possible to put type hint in chained assignments?

这两次try 都失败了:

>>> def foo(a:int):
...     b: int = c:int = a
  File "<stdin>", line 2
    b: int = c:int = a
              ^
SyntaxError: invalid syntax
>>> def foo(a:int):
...     b = c:int = a
  File "<stdin>", line 2
    b = c:int = a
         ^
SyntaxError: invalid syntax

2.- Is it possible to put type hint in multiple assignments?

以下是我的try :

>>> from typing import Tuple
>>> def bar(a: Tuple[int]):
...     b: int, c:int = a
  File "<stdin>", line 2
    b: int, c:int = a
          ^
SyntaxError: invalid syntax
>>> def bar(a: Tuple[int]):
...     b, c:Tuple[int] = a
... 
  File "<stdin>", line 2
SyntaxError: only single target (not tuple) can be annotated
>>> def bar(a: Tuple[int]):
...     b, c:int = a
... 
  File "<stdin>", line 2
SyntaxError: only single target (not tuple) can be annotated

我知道,在这两种情况下,类型都是从a的类型提示推断出来的,但我有一个很长的变量列表(在类的__init__中),我希望是额外显式的.

我使用的是Python 3.6.8.

推荐答案

  1. 正如第PEP 526节"拒绝/推迟的建议书"中明确指出的,不支持链式作业(job)中的注释.引用政治公众人物的话:

    This has problems of ambiguity and readability similar to tuple unpacking, for example in:
    x: int = y = 1
    z = w: int = 1
    it is ambiguous, what should the types of y and z be? Also the second line is difficult to parse.

  2. 对于解包,按照相同的PEP,应该在赋值之前为变量放置裸注释.政治公众人物的例子:

    # Tuple unpacking with variable annotation syntax
    header: str
    kind: int
    body: Optional[List[str]]
    header, kind, body = message
    

Python-3.x相关问答推荐

如何获得给定列表中所有可能的元素组合?

如果行在所有上级索引中都为0,如何删除下级索引行?

将字符串转换为python日期时间时出错

Django 3.2/Django-cms 3.11:查找错误:型号帐户.客户用户未注册

如何从选定的html内容中获取所需的文本

如何将项目添加到Python中具有固定大小的列表列表中

如何在 python 中将带有时区信息的时间戳转换为 utc 时间

可以在 Python 的上下文管理器中调用 sys.exit() 吗?

如何查找以开头并替换的字符串

为什么不能用格式字符串 '-' 绘制点?

双轴上的刻度和标签

如果值超出上下限(异常值处理),则将值的数据框替换为 np.nan

Python.在循环中填充字典的问题

从 h264 帧解析数据包时 PyAV 不一致

如何在 VSCode 的在 Cloud Run Emulator 上运行/调试构建设置中添加 SQL 连接

使用一周的特定第一天将每日日期转换为每周

PyQt:退出时没有错误消息(回溯)

为什么 2to3 将 mydict.keys() 更改为 list(mydict.keys())?

连接 dict 值,它们是列表

在 Meta 中创建具有动态模型的通用序列化程序