Use SimpleNamespace for better readability

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

Code

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

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.

Uses

>>> data = {"a": 1, "b": 2, "c":3} 
>>> data["a"] 1
>>> data_simple = SimpleNamespace(**data)
>>> data_simple namespace(a=1, b=2, c=3)
>>> data_simple.a 1
>>> data_simple.b 2
>>> data_simple.c 3
>>>

Hope you have learned something from this post. Please share your valuable feedback with afsal@parseltongue.co.in

Originally published at https://parseltongue.co.in on September 2, 2022.

--

--

Coding, Reading,Python

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store