What’s this weird arrow notation in Python?

What’s this weird arrow notation in Python?

Find out how Python 3?s function annotations can help you write clearer, more human-friendly Python functions.

Image for post

Straight as an arrow

If you?ve been developing Python applications for any length of time, you?ll occasionally find corners of the language that you?re not immediately familiar with. Python 3 makes this a little more common for newer developers ? because Python 3 introduces a whole body of new enhancements and features that improve the language and extend its flexibility.

If you?re working through a Python 3 codebase, you might wander upon a function that looks something like this:

def useful_function(x) -> int: # Useful code, using x, here return x

At first, this is weird. Python doesn?t use arrow notation, like JavaScript ? so what is this arrow doing? This, friend, is a return value annotation, which is part of function annotation, and it?s a feature of Python 3 – and has been here since 3.0!

Cool? but what does that mean?

Simply put, it?s documentation!

Return value annotations are a way to document your code elegantly in-line, by allowing you to simply describe the data type of the ?thing? the function returns. This is effectively a direct equivalent to Python 2?s docstrings ? but it?s sleeker and helps other developers to understand what your functions are kicking out at a quick, cursory glance. Nice!

Takeaways

So, some key takeaways, so you can get started with making your functions clearer and more readable than ever:

  • Python doesn?t really interact with them ? it pretty much populates and ignores the annotation, but it?s available in your function?s metadata, which can be useful if you?re doing unusual or tricky stuff that relies on knowing what a function?s return type is.
  • The information is available as an .__annotations__ attribute on the function, which is a dictionary. So, in our code above, that looks like: useful_function.__annotations__[?return?] ? which should give you ?int?.
  • Additional context: Because Python doesn?t really do anything with the data, when first introduced in 3.0, it was a pretty loose idea ? and you?d see functions with annotations that were not datatypes, like int, dict or list. You could put whatever you liked in there. After Python 3.5, however, this approach is being strongly discouraged in favour of ensuring that an annotation describes a datatype, and not an arbitrary measure in a programmer?s mind. Stick to data types to keep your code clean and the community happy. 🙂

And now for some homework ? hop on over to Parameter Annotations, and find out how they can help you too.

Happy coding! 🙂

11

No Responses

Write a response