converting dict to object

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Dec 2 21:10:04 EST 2006


On Sat, 02 Dec 2006 17:00:15 -0800, John Machin wrote:

> 
> Steven D'Aprano wrote:
>> 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).
>>
> [snip]
>> 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.
> 
> but getattr() needs strings.

Well, that's true, but if the dict is being read from a file or with
raw_input, the keys will naturally be strings. But even if it is some
arbitrary dict, the keys still don't need to be checked for valid
identifiers, merely checked for strings. And again, keeping the
keys/values in a dict instead of converting to object attributes naturally
solves that problem -- or rather, it isn't a problem that needs to be
solved.

Either way, I see no advantage to taking an arbitrary dict and converting
it into object attributes. It sounds to me like "when the only tool you
have is Java, everything looks like an object attribute" coding :-)

I'd suggest that the "right" answer to the OP's original question "How
do I convert a dict to object attributes?" is "Don't do that", regardless
that it is technically possible.

Maybe I'm wrong and there are lots of really handy uses for such a tactic.
Can anyone suggest any?



-- 
Steven.




More information about the Python-list mailing list