In Python should we set Optional[str] = None in the argument list?

Question:

My coworker said the code I wrote crashed recently and that was because in the function’s argument list I did not specify Optional[str] = None. I only have Optional[str].

So basically my function looks like this:

def a(b: Optional[str]):
    if b is None:
        <do something>
    else:
        <do something>

I always thought default for Optional argument is None, so I did not specify the default value. It did not crash for me but crashed for my coworker, so I’m kinda confused.

My python version is >=3.

Asked By: hpnhxxwn

||

Answers:

As mentioned in the above comments, Optional[str] is a type-hint to be used by IDEs and other static analysis tools, not a default argument. If you want to make a default argument such that you can call the function with a(), then you do need to add = None as you proposed. That could be a reasonable approach if you expect this function to be called with an omitted argument, but that will depend on your design and architecture.

Answered By: BowlingHawk95

Giving a bit more update response.

From mypy documentation:

PEP 604 introduced an alternative way for spelling union types. In Python 3.10 and later, you can write Union[int, str] as int | str. 

Python docs) are also pointing the new syntax as a way of settings a field as optional.

str | None == typing.Optional[str]

It seems Tiangolo, creator of FastAPI an a well-respected python developer at the time of this writing, also advocates for it.

Should you consider this the truth? I think this is still a matter of opinion as both are supported. The only biggest change in mypy recently is that it does not allow assigning None as the default value if it is not marked as Optional or a Union[ Any | None].

Answered By: fsan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.