pythonpycharmlintdocstring

Can you pass a None argument when docstring requires a string?


Ok, this question has probably been answered somewhere but my Google-fu hasn't found the right combination of keywords yet.

I have a function that accepts a string, but when I pass None, Pycharm's inspection is flagging a type error. Is this an error in the linter? Does None count as a string? I know I can call the function with an empty string, but I think I should be able to use None as well.

def my_func(some_str):
""" does something
Arguments:
some_str (str): a string
"""
    # do something

...

my_func(None)  <-- throws Expected type 'str', got 'None' instead

Solution

  • As a dissenting opinion, Python is not strongly typed so for pycharm's linter to highlight that as an error seems a little odd to me.

    Of course there are many functions which legitimately need a string, but I'm sure i saw somewhere that 'good practice' for that was a function that looked more like this:

    def myfunct(s):
        try:
            s = str(s)
        except TypeError:
            raise TypeError('message explaining function usage')
        # actual function
    

    This works with anything that can be coerced into a string, which seems more sensible than requiring literally a string.

    Am I nuts?