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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With