Fix Python – How to know function return type and argument types?


Asked By – Rabarberski

While I am aware of the duck-typing concept of Python, I sometimes struggle with the type of arguments of functions, or the type of the return value of the function.

Now, if I wrote the function myself, I DO know the types. But what if somebody wants to use and call my functions, how is he/she expected to know the types?
I usually put type information in the function’s docstring (like: "...the id argument should be an integer..." and "... the function will return a (string, [integer]) tuple.")

But is looking up the information in the docstring (and putting it there, as a coder) really the way it is supposed to be done?

Edit: While the majority of answers seem to direct towards “yes, document!” I feel this is not always very easy for ‘complex’ types.
For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?
The docstring PEP documentation doesn’t give any guidelines on that.
I guess the counterargument will be that in that case classes should be used, but I find python very flexible because it allows passing around these things using lists and tuples, i.e. without classes.

Now we will see solution for issue: How to know function return type and argument types?


This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor – anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source.

Here are some strategies to avoid problems with duck typing:

  • create a language for your problem domain
  • this will help you to name stuff properly
  • use types to represent concepts in your domain language
  • name function parameters using the domain language vocabulary

Also, one of the most important points:

  • keep data as local as possible!

There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don’t have weird parameter types coming from far away that you can’t figure out by looking in the vicinity of the code…

Related, (and also related to docstrings), there is a technique in python called doctests. Use that to document how your methods are expected to be used – and have nice unit test coverage at the same time!

This question is answered By – Daren Thomas

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0