DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

Type hints in Python (3)

Buy Me a Coffee

*Memo:

The variable with a type hint and no value is possible while the variable with no type hint and value is impossible as shown below:

v: str

v = 'Hello'
Enter fullscreen mode Exit fullscreen mode
v: str

print(v)
# NameError: name 'v' is not defined
Enter fullscreen mode Exit fullscreen mode
v
# NameError: name 'v' is not defined
Enter fullscreen mode Exit fullscreen mode

The value None should be used as a type within a type hint because the type NoneType gets error as shown below:

v: None
# No error
Enter fullscreen mode Exit fullscreen mode
from types import NoneType

v: NoneType
# error: NoneType should not be used as a type, please use None instead
Enter fullscreen mode Exit fullscreen mode

With print(), printing the return value from the function which only returns None gets the error as shown below:

*Memo:

  • The error occurs both with and without --strict.
  • The error can be disabled using --disable-error-code with func-returns-value:
    • mypy --strict --disable-error-code func-returns-value test.py.
    • mypy --disable-error-code func-returns-value test.py.
  • Just calling but not printing the function doesn't get the error.
  • I reported the strange behaviour as the issue.
def func() -> None:
    return None

print(func())
# error: "func" does not return a value (it only ever returns None)
Enter fullscreen mode Exit fullscreen mode
def func() -> None:
    return None

func()
# No error
Enter fullscreen mode Exit fullscreen mode

Multiple variables cannot be defined with type hints at once so they need to be type-hinted first as shown below:

v1: str
v2: str

v1 = v2 = 'Hello'

print(v1) # Hello
print(v2) # Hello
Enter fullscreen mode Exit fullscreen mode
v1: str = v2: str = 'Hello'
# SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

Assignment statement unpacking cannot be done with type hints at once so variables need to be type-hinted first as shown below:

v: str

v, = 'Hello',

print(v) # Hello
Enter fullscreen mode Exit fullscreen mode
v1: str
v2: int

v1, v2 = 'Hello', 23

print(v1) # Hello
print(v2) # 23
Enter fullscreen mode Exit fullscreen mode
v: str, = 'Hello',
v1: str, v2: int = 'Hello', 23
# SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

for statement unpacking cannot be done with type hints at once so variables need to be type-hinted first as shown below:

v: str

for v, in [['A'], ['B'], ['C']]:
    print(v)
# A
# B
# C
Enter fullscreen mode Exit fullscreen mode
v1: str
v2: int

for v1, v2 in [['A', 0], ['B', 1], ['C', 2]]:
    print(v1, v2)
# A 0
# B 1
# C 2
Enter fullscreen mode Exit fullscreen mode
for v: str, in [['A'], ['B'], ['C']]: pass
for v1: str, v2: int in [['A', 0], ['B', 1], ['C', 2]]: pass
# SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

Top comments (0)