Cool object trick

Steve Holden steve at holdenweb.com
Fri Dec 17 16:10:51 CET 2004


Fredrik Lundh wrote:

> Steve Holden wrote:
> 
> 
>>>Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon,
>>>obj.sausages, "and", obj.spam' a lot easier ;-)
>>>
>>
>>Of course this whole thing of substituting attribute access for dictionary keys only works as long 
>>as the keys are strings with the same syntax as Python identifiers, so one shouldn't go completely 
>>overboard.
> 
> 
> unless you're willing to use getattr() for thos oddball cases, of course.
> 
Of course.

>     >>> class Dummy:
>     ...     pass
>     ...
>     >>> x = Dummy()
>     >>> setattr(x, "spam&egg", "hello")
>     >>> getattr(x, "spam&egg")
>     'hello'
>     >>> x.spam&egg
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>     AttributeError: Dummy instance has no attribute 'spam'
> 
> but seriously, turning container elements into attributes should only be done
> if it makes sense from a design perspective.  (and vice versa; you shouldn't
> use a dictionary if an object would make more sense -- but attribute abuse
> is a lot more common)
> 
Really we are talking about the outer limits here. Anyone preferring

     setattr(x, "spam&egg", "hello")

to

     x["spam&egg"] = "hello"

when it isn't necessary clearly doesn't share our two principal 
attributes: an elegant sense of design, fine knowledge of Python and an 
    inherent modesty.

Sorry: out *three* principal attributes. Bugger, I'll come in again.

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list