Python Friday #133: Minimalistic DTOs in Python

I needed to return multiple values from a function. While Python allows that with tuples, it is a lot of magic involved and the meaning in the order of values in the tuple is nowhere written down. Is there a better way to create a data transfer object without much effort? Let’s find out.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Named tuples to the rescue

We could create a full-blown class for our task. However, there is a way with less typing and the added benefit of immutability: the NamedTuple type. As with a tuple, we cannot modify the values after we created the tuple. But as the name suggests, we can give intention revealing names to the values:

The : str are type annotations. They show up in VS Code when we create an instance of the class Link:

The type annotations help you to enter the right data in VS Code

We can use our named tuple like this:

url: http://127.0.0.1/home
text: Home

We now can pass our instance between functions without worrying that we may accidently modify a value. If we try, we get this error:

Traceback (most recent call last):
File “C:\PythonFriday\helper\named_tuple_example.py”, line 14, in
home.text = “new”
AttributeError: can’t set attribute

 

Conclusion

Named tuples are a helpful way to create data transfer objects. We need to inherit from NamedTuple and otherwise do not need to write much boilerplate code.

1 thought on “Python Friday #133: Minimalistic DTOs in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.