Alternate Syntax for dictionary elements

Emile van Sebille emile at fenx.com
Tue Jul 3 14:56:41 EDT 2001


You can get this effect now by leveraging a minimal class:

class Dict:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

dict = Dict( type = 'button', id= 32, name = 'some name' )

if dict.type == 'button':
    print "This works!"

dict.newType = 2

if dict.newType == 2:
    print "So does this"

print repr(dict.__dict__)


If you don't need to initialize the object with named parameters, you can
simplify to using:

class Dict:
    pass


HTH,

--

Emile van Sebille
emile at fenx.com

---------
"Gerson Kurz" <gerson.kurz at t-online.de> wrote in message
news:3b421046.1836046 at news.t-online.de...
> Please consider the following:
>
> dict = { 'type' : 'button', 'id': 32, 'name' : 'some name' }
> ...
> if o['type'] == 'button':
> # do something for objects of type button
>
> Now, take a look at
>
> if o.type == 'button':
> # do something for objects of type button
>
> A dictionary can in many cases be interpreted as a dynamically created
> object. And an object should have members; or rather, you should be
> able to access its data in a member-style fashion.
>
> This change doesn't save you much type overhead - but it makes the
> code look more readable for those uses for which it makes sense to
> treat dictionarys as dynamic objects (and I have lots of uses for
> these).
>
> I realize that there are possible dictionary keys (such as tuples) for
> which such a syntax is improper; it should be sufficient to make the
> following restrictions:
>
> - the syntax is only possible for string-typed keys that *qualify as
> valid identifiers*
> - the syntax is only possible for keys that are not part of dir({}).
>
> The implementation would be a hack that extendes the {}.__methods__
> lookup.
>
> Worthwile pursuit or total crap ?
>





More information about the Python-list mailing list