1

I have a REST API that I want to model in a class so I can access the properties using the dot notation (JS list notation). I explicately defined the properties on my class using the @property tags over the known properties of the returned JSON, but since I am modelling a 3rd part API, I need a way to also dynamically add properties if they are not present in the class. I do not want to inherit from dictionary because this doesn't play well with defined properties. They seem to return as None most of the time. I also do not want the users to have two ways of getting at the information (trying to follow the zen of python). Dot notation is fine, they don't need to be able to access the data via KEY names.

Using setattr might be a possible location at run time, but I think I need an additional step because the compiler throws a not implemented error if a property does not exist on the class. Should I implement __setattr__ and __setattribute__ on the object to prevent this error and just return None if the property does not exist.

I only need to support read-only.

Thank you

2 Answers 2

1

What I did was use self.__dict__.update(json) which copies items in the JSON dict into the object's dict and so they appear as properties of the object. The client can then use dot notation to access or mutate them.

1
1

Can you expand on what you mean by dynamically add properties? I take it that you need to do this while code is running, rather than simply edit the source files?

If so maybe check out named tuples as part of the Python collections module

https://docs.python.org/2/library/collections.html

You can create a class dynamically like this

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

and then create objects from that class

record = EmployeeRecord('Bob', 34, 'manager', 'IT', 'Senior')
print record.name
print record.age

You can wrap this in code that fetches the data structure from the API and dynamically creates the class each time based on the current data structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.