Search code examples
pythonpep8pylance

Phython: missing-function-docstring (pylance)


Im getting the message from pylace at my function. What to do?

def retangulo(larg, comp):
   
    area = larg * comp
   
    print(f'A área de um terreno {larg} x {comp} é {area}.')

docstringpylint(missing-function-docstring)

I am expecting to understand how to write python the "right way".


Solution

  • ... write python the "right way".

    That is certainly commendable. Not sure I'd want to insist on a """docstring""" on every function though, since some, like this one, are already pretty self-explanatory.

    The missing-function-docstring diagnostic is inviting you to add a single sentence of documentation, such as this:

    def retangulo(larg, comp):
        """Displays the area of a rectangle, given its two sides."""
        area = larg * comp
        print(f'A área de um terreno {larg} x {comp} é {area}.')
    

    Consider linting with flake8 instead. It is not too picky. When I find it complaining, I usually agree with its complaint, so I fix things up at once to ensure it remains silent.


    Consider running black . before linting, to automatically fix up minor whitespace issues.


    Consider throwing in an optional type hint or two:

    def retangulo(larg: int, comp: int) -> int:
    

    Remember that python does not do any runtime checking / enforcement of types, so retangulo(1, math.pi) would still "work". The mypy static analysis checker would dutifully complain about such a call.

    Or, since the concepts of length and area are defined across non-negative real numbers, it would no doubt be better to declare like this:

    def retangulo(larg: float, comp: float) -> float:
    

    You don't have to use type hints, and if you do you certainly don't have to use them everywhere.

    But in addition to their concise documentation value to humans, and the linting value of a mypy run, they can play very nicely with IDEs, such as PyCharm. When you type foo. CTRL-SPACE and hope to see some auto-completion suggestions, the type of foo matters. And hints help the IDE to make relevant suggestions. For example, if the IDE knows that foo is a regex, it might suggest .findall( as a completion, which is quite different from what it would do with a str variable.