1

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:

  1. What should the default be in do_something_1 if None is rejected by mypy checks?
  2. What is the benefit of do_something_2 over do_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
evanstjabadi
  • 305
  • 3
  • 10
  • 1
    Does this answer your question? [Can I omit Optional if I set default to None?](https://stackoverflow.com/questions/62732402/can-i-omit-optional-if-i-set-default-to-none) – MisterMiyagi Feb 28 '22 at 15:00

1 Answers1

2

In python, the value None which you want to assign as default value, is of a special type NoneType, which is not compatible with any other type, to avoid explicitly errors where you call methods on None objects (much like Java NullPointer` runtime errors).

This obviously isn't an issue when using standard Python (which does no checking at all on the types), but poses a problem when using typing.

The possible solutions are:

  • Use an Optional (as you did, so that your input variable can either be a MyInt or None)
  • Make MyInt inherit from NoneType (probably not what you want)
rikyeah
  • 1,896
  • 4
  • 11
  • 21