Following is my requirement which is to be implemented in python: I have a dictionary called context which will be updated from various parts of the program.
Now I have to create an obj called env
which holds the dictionary context and environmental variables dictionary also.
env
object should have all features of dictionary class along with it, it should be possible to the access the item of dictionary as attribute of the object.
For example,
context = {'install_path' : '/home/xyz','cwd' : '/home/xyz/Desktop'}
the
context
dictionary will be updated from various parts of program.
Now I have to create env
object which holds context dictionary and also environmental dictionary. And It should be possible to access the items of dictionary as attributes of env
object.
For example:
print(env.install_path) # accessing item of context dictionary
print(env.os) #accessing environmental variable print(env)
print(env['install_path'])
print(env)
should produce output as:
/home/xyz linux /home/xyz {'install_path':'/home/xyz','cwd':'/home/xyz/Desktop'} all envrionmental variables
Later when the context dictionary is updated the env
object should also be updated.
Please help how to achieve this.
Create a subclass of dict.
Objects have methods that get called if an attribute is missing. You can override the default implementation of these methods to do dictionary get and set operations.
Previous discussion here
If you need to create a new AttributeDict from an existing dictionary, you can use the following:
If you want a different object that just references an existing dictionary, use this
Something like this should do the trick:
Usage:
This is the simplest way to do something like that I've seen:
Output: