Names don't have types; only the values they refer to have types. In this case, it is perfectly normal to document that str_arg_1
will refer to a str
object or None
, with an explanation of what each means. As far as a docstring is concerned, it's safe to say everyone will understand what you mean if you state that an argument that should be a str
may also take None
.
In PEP-484, which deals with providing statically checkable type usage, this notion of using None
is not just acceptable, but catered to.
If str_arg_1
should always be a string, you would hint it as
def example_method(str_arg_1: str):
If it is allowed be None
as well, you would indicate that with a union type
def example_method(str_arg_1: Union[str, None]):
As this is a very common case, there is a shortcut for indicating this:
def example_method(str_arg_1: Optional[str]):
In fact, if the default value is None
, the static checker that uses these type annotations assumes the use of Optional
, so the following are equivalent:
def example_method(str_arg_1: Optional[str] = None):
def example_method(str_arg_1: str = None):