Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 319
hpnhxxwn Avatar asked Jan 27 '23 14:01

hpnhxxwn


1 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.

like image 186
BowlingHawk95 Avatar answered Jan 31 '23 21:01

BowlingHawk95