0

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

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

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

NBajanca
  • 3,544
  • 3
  • 26
  • 53

1 Answers1

4

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):
chepner
  • 497,756
  • 71
  • 530
  • 681