I’m creating a Python class as an API to objects managed remotely via REST.
The REST API includes a call that returns a list of dictionaries that define properties of the remote objects. I’m in the process of writing code to dynamically add these properties as attributes of the corresponding Python objects (ie: when the class is instantiated, a REST query is made for a list of properties each of which is then added as an attribute on the instance.)
However, this brought back memories of PHP code I’d once glanced at that dynamically added attributes to objects and thinking “have you heard of dictionaries??”
Given my background is rooted in C/C++/Java this is a somewhat foreign idea to me, but is perhaps par for the course in Python (and PHP). So, when is it appropriate to dynamically add attributes to an object rather than using a dictionary?
From what I’ve read in related material, it seems to me an API is a legitimate case.
disclaimer: I know nothing about REST …
That said, I would typically be a little hesitant to add attributes to an object willy-nilly for the following reasons:
obj.__dict__orvars(obj)or something similar.There is precedence for adding attributes in the standard library however … That’s basically what
argparsedoes to populate the returnednamespace. I think that perhaps it is worth asking the question: “Will the user know which attributes are going to be added to the object?”. If the answer to this question isyes, and you’re not worried about the afore mentioned namespace conflicts, then perhaps a simple object is appropriate, otherwise, I’d just use a dictionary.