Alternate Syntax for dictionary elements

Quinn Dunkan quinn at
Tue Jul 3 21:25:31 CEST 2001

On Tue, 03 Jul 2001 18:45:05 GMT, Gerson Kurz <gerson.kurz at> wrote:
>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

Won't work because of {}.keys, etc.  If you don't mind those name clashes, you
could write __getattr__ and __setattr__ to simulate this.  It's not advisable,
though, because container access is a clearly seperate concept from object
access in python.  It has a different syntax and a different conceptual
purpose, even though there is some implementation overlap (e.g. o.__dict__).
If you want object access notation, you should probably be using an object,
not a dictionary.  For example, your button above is probably not suited for

In Lua, on the other hand, tables and objects are truly the same, and
is syntactic sugar for foo['bar'].  Lua's object model is rather weaker and
more do-it-yourself than python's, though.

And here's why using a dict as you did above is probably silly: You don't need
to manually encode type information if the language can do it for you.  Making
a Button class will automatically attach that type to its instances.
Furthermore, a fundamental property of all objects (as opposed to true values
like an algebraic data type) is that they have unique ids seperate from their
values.  The language will maintain them for you, and to fetch them you can
use the id() function.  The 'name' field is the only necessary one.

"Yes", you're saying, "but it was only an example." :)

More information about the Python-list mailing list