Skip to content

#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.

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:

1
2
3
4
5
from typing import NamedTuple

class Link(NamedTuple):
    url: str
    text: str

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:

1
2
3
4
home = Link("http://127.0.0.1/home", "Home")

print(f"url: {home.url}")
print(f"text: {home.text}")

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:

home.text = "new"

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.