NBajanca NBajanca - 1 year ago 64
Python Question

Python - Should there be made an attempt to be consistent with the arg type in optional args?

My doubt is simple. Should I do an effort to be consistent with argument types when using optional arguments?

An example:

def example_method(str_arg_1=None):
if str_arg_1 is not None:
# do something

is allways a
,except when it is not passed in the method call, so I'm not sure if is a good practice to use
in this case.

I came to this doubt because I don't know how to write my docstrings, is the
even if sometimes is

Answer Source

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):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download