*Memo:
- My post explains type hints (1).
- My post explains type hints (2).
- My post explains type hints (4).
- My post explains type hints (5).
- My post explains type hints (6).
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'
v: str
print(v)
# NameError: name 'v' is not defined
v
# NameError: name 'v' is not defined
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
from types import NoneType
v: NoneType
# error: NoneType should not be used as a type, please use None instead
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)
def func() -> None:
return None
func()
# No error
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
v1: str = v2: str = 'Hello'
# SyntaxError: invalid syntax
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
v1: str
v2: int
v1, v2 = 'Hello', 23
print(v1) # Hello
print(v2) # 23
v: str, = 'Hello',
v1: str, v2: int = 'Hello', 23
# SyntaxError: invalid syntax
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
v1: str
v2: int
for v1, v2 in [['A', 0], ['B', 1], ['C', 2]]:
print(v1, v2)
# A 0
# B 1
# C 2
for v: str, in [['A'], ['B'], ['C']]: pass
for v1: str, v2: int in [['A', 0], ['B', 1], ['C', 2]]: pass
# SyntaxError: invalid syntax
Top comments (0)