Use SimpleNamespace for better readability

Posted by Afsal on 02-Sep-2022

Hi Pythonistas!

Today we are going to learn a simple technique that increases code readability. Which is to use a simplenamespace for better code readability. In a previous post, we mentioned using namedtuple for better readability. This is also a similar idea but the difference lies is in namedtuple is good for data with a well-defined structure. But namespace can be used for the dynamic structure. Let us learn with code


from types import SimpleNamespace
>>> person = SimpleNamespace(name="guido", age=15)
>>> person
namespace(name='guido', age=15)
>>> person.age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'types.SimpleNamespace' object has no attribute 'email'
>>> = ""
>>> person
namespace(name='guido', age=15, email='')

In the above example we can see that create an object person with a name and age. We can easily access the using the field name. Also, we can add new attributes dynamically to the object.


  • Simplenamespace can be used to convert JSON to object. So that accessing look more cleaner
>>> data = {"a": 1, "b": 2, "c":3}
>>> data["a"]
>>> data_simple = SimpleNamespace(**data)
>>> data_simple
namespace(a=1, b=2, c=3)
>>> data_simple.a
>>> data_simple.b
>>> data_simple.c
  • Simplename space can be used to make mock objects for testing applications

Hope you have learned something from this post. Please share your valuable feedback with