converting dict to object

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Dec 2 19:58:42 EST 2006


On Sat, 02 Dec 2006 12:16:24 -0800, John Machin wrote:

> The OP might consider adding code to the __init__ method to check for
> cases where the dictionary key is not a string containing a valid
> Python identifier (not a keyword).

If the OP is doing something like this:

attributes = {"length": 15, "id": 2345}
# attribute names are known at compile time, created by the coder
obj.__dict__.update(attributes)
print obj.length
print obj.id

then checking that "length" and "id" are valid identifiers is hardly
necessary, any more than this would be:

class Spam:
    def __init__(self, length, id):
        check_valid_indentifier("length")
        self.length = length
        check_valid_indentifier("id")
        self.id = id


But if he's doing something like this:

attributes = fetch_user_dict()
# attribute names aren't known until runtime
obj.__dict__.update(attributes)
for key in attributes:
    print getattr(obj, key)

then it is also redundant to check for valid identifiers, since getattr()
doesn't need them. However, one might still need to test for accidental
clashes with pre-existing object attributes.

On the third hand, if that's the case then there seems to be no real
advantage to converting the dict into object attributes. Why not just
delegate to a saved copy of the dict?

class Spam:
    def __init__(self, d):
        self._d = d
    def __getitem__(self, key):
        return self._d[key]
    def __setitem__(self, key, value):
        self._d[key] = value

s = Spam({"a": 1, "something else": 2})
s["a"]
s["something else"]




-- 
Steven.




More information about the Python-list mailing list