Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hints and chained assignment and multiple assignments

I guess these two questions are related, so I'll post them together:

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

These two attempts failed:

>>> 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?

These were my attempts:

>>> 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

I am aware that in both cases the type is inferred from the type hint of a, but I have a long variable list (in the __init__ of a class) and I want to be extra-explicit.

I am using Python 3.6.8.

like image 639
steffen Avatar asked Jun 15 '19 16:06

steffen


People also ask

What is chained assignment Python?

In Python, assignment statements are not expressions and thus do not have a value. Instead, chained assignments are a series of statements with multiple targets for a single expression.

What is multiple assignment in Python?

Python allows you to assign a single value to several variables simultaneously. For example − a = b = c = 1. Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

What are type hints?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.


1 Answers

  1. As explicitly stated in PEP 526, section "Rejected/postponed proposals", annotations in chained assignments are not supported. Quoting the PEP:

    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. For unpacking, per the same PEP, you should place bare annotations for your variables before the assignment. Example from the PEP:

    # Tuple unpacking with variable annotation syntax
    header: str
    kind: int
    body: Optional[List[str]]
    header, kind, body = message
    
like image 66
Mikhail Burshteyn Avatar answered Sep 21 '22 19:09

Mikhail Burshteyn