Should I specify the type of return of a procedure in Python?

Asked

Viewed 102 times

2

For some time I have studied and learned a little more about Python. I recently read an article about the description of python typing using the module typying. Since I learned about this feature I try to improve the code by adding this feature in order to improve the documentation and also the maintenance.

A few days ago, with the addition of this resource, I came across a question about how best to describe a procedure. I imagined that by the knowledge I possess so far the best way would be the following.

def foo() -> None:
    pass

But talking to a friend, I realized that this form might not be the best since because it is a procedure, we start from the definition that during the execution we will not return any object, not even the object None.

Then comes the form already known:

def foo():
   pass

that meets the desired objective of describing the procedure, but we still do not have a clear description that this function will be a procedure, therefore it will not return anything.

Even know a little more about an updated and complete form in terms of job description and procedure documentation?

1 answer

3


Python allows you to use explicit typing. It doesn’t mean that it has become a static typing language, but it helps to make the code more readable and even catch some errors some extra tools.

Each one adopts a style that makes more sense to you. I think it should be consistent, or adopt typing or not. Nothing prevents you from using both and it can even make sense to adopt only in some very specific cases or the opposite and fail to adopt the typing only when you want it to be dynamic even, that is, only when you know that the variable can have values of more than one type.

If you use without criterion it doesn’t make much sense, it loses value.

I see more people not adopting typing, which makes sense for scripts. But today many people use Python as if it were not a language of script, then the typing starts to be more important. So because people like to use the same tool for everything ends up getting complicated establishing the best way.

Um tipo de canivete suíço com machado, martelo, etc.

If you adopted typing whenever possible then I think it should be consistent.

Python only has functions and the procedure is simulated returning nothing, even if implicitly.

When you do a procedure, which is actually a function that returns nothing, and decided to be explicit in typing, then there’s only one consistent way to write this code:

def foo() -> None:
    pass

It’s a mistake to say that something that doesn’t have one return explicit does not return even a None, because it returns:

def foo():
   pass

print(foo())

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.