I have some code similar to the below one. In do_something_1
, I want to set the default_value
for my_int
to be None
so that I can do some logic on it later. But mypy
throws this error:
Incompatible default for argument "my_int" (default has type "None", argument has type "MyInt")
However, when I change to Optional
like in do_something_2
, everything works well.
My questions are:
- What should the default be in
do_something_1
ifNone
is rejected bymypy
checks? - What is the benefit of
do_something_2
overdo_something_1
?
from typing import Optional
from pydantic import BaseModel
class MyInt(BaseModel):
value: int
def do_something_1(my_int: MyInt = None):
if my_int is not None:
print("Value:", my_int.value)
else:
print("no value")
def do_something_2(my_int: Optional[MyInt] = None):
if my_int is not None:
print("Value:", my_int.value)
else:
print("no value")
# do_something_1()
do_something_1(my_int=MyInt(value=1))
# >>> Value: 1
# do_something_2()
do_something_2(my_int=MyInt(value=2))
# >>> Value: 2