*Memo:
- My post explains type hints (1).
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
The function which only returns None gets the error if defining and calling the function, and printing the return value as shown below:
*Memo:
- 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.
-
- Only defining and calling the function doesn't get the error.
- Only defining 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)
from types import def func() -> None:
return None
func()
# No error
def func() -> None:
return None
# 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
complex accepts float, int and bool, float accepts int and bool and int accepts bool as shown below:
*Memo:
-
PEP 484 explains the numeric tower of
complex,floatandint. -
The doc explains
boolis the subclass ofint.
<complex>:
v: complex = 2.3+4.5j # complex
v = 2.3 # float
v = 23 # int
v = True # bool
# No error
<float>:
v: float = 2.3 # float
v = 23 # int
v = True # bool
# No error
v = 2.3+4.5j # complex
# Error
<int>:
v: int = 23 # int
v = True # bool
# No error
v = 2.3+4.5j # complex
v = 2.3 # float
# Error
<bool>:
v: bool = True # bool
# No error
v = 2.3+4.5j # complex
v = 2.3 # float
v = 23 # int
# Error
Top comments (0)