DEV Community

Discussion on: Best practice for Python returns

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

In most cases, the 'de-facto' standard for Python is:

  • If the function worked, return the result if there is one, otherwise return nothing (unless the below point applies to some possibilities, in which case return True).
  • If the function ran into an issue that the caller is supposed to be watching for which is not potentially fatal, return something distinct from a valid result to indicate that.
  • If the function ran into some actually fatal error, throw an appropriate exception (ideally not one of the generic ones unless it's something that truly is an exact match like a type or value error in the parameters) instead of returning anything.

For complex return values:

  • Tuples are usually used for structured data with a fixed number of fields each having a pre-defined purpose (for example, representing a date as a tuple with each field of the date individually accessible), or when you specifically need to return an immutable sequence (which is rare in Python). Note that returning a tuple implies to many people that you will always be returning a tuple of the same size.
  • For simple groups of return values, lists are the norm, though you may also see deques, generators, or custom sequence classes used on occasion. The important thing though is that the result is iterable, because that's usually what the caller is going to want to do with it.
  • In some rare cases, a Set may be returned for a collection of return values, but this is typically only used in cases where the whole API is dealing primarily with sets of values.
  • Dictionaries and other mapping types are only used for structured data or to directly replicate API's that return structured data.

Regardless, the most important thing here is to make your code consistent. Pick an approach and stick to it. I would encourage you to look at some of the bigger projects written in Python for ideas on this though.

Collapse
 
belfinwe profile image
joakimRN

Thank you for such a in depth reply :D
I'll have to read this a few times, and look up some things I have not encountered in Python before :)
Looking forward to testing out what you have suggested, and I will try to stay consistent in my projects to come.