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
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
- Simplenamespace can be used to convert JSON to object. So that accessing look more cleaner
>>> 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
>>>
- 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 afsal@parseltongue.co.in