Type hints when unpacking a tuple?

11,564

According to PEP-0526, you should annotate the types first, then do the unpacking

a: int
b: int
a, b = t
Share:
11,564

Related videos on Youtube

Cai
Author by

Cai

Internet resident.

Updated on June 12, 2022

Comments

  • Cai
    Cai about 2 years

    Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a SyntaxError:

    from typing import Tuple
    
    t: Tuple[int, int] = (1, 2)
    a: int, b: int = t
    #     ^ SyntaxError: invalid syntax
    
  • tribbloid
    tribbloid over 5 years
    Still triggers a warning: Redeclared 'a' defined above without usage
  • joel
    joel over 3 years
    @tribbloid I get that when I have indeed already defined a earlier, are you certain you haven't done that?
  • normanius
    normanius about 3 years
    @tribbloid This is if the variable is redefined, like a = int(a) or other re-assignments. If you work with mypy for static type checking, use --allow-redefinition to avoid the warning
  • g.pickardou
    g.pickardou about 2 years
    this is sad, how on earth <variable>:<typehint> can not use any syntactical context, where variable assignment is legal...