[CentralOH] Syntactic Sugar (or sacharine)?

Eric Floehr eric at intellovations.com
Fri Aug 12 19:03:32 CEST 2011


Mark,

You've independently implemented Ruby symbols in Python :-).  Symbols
are one of the few areas where Ruby and Python differ.  Symbols in
Ruby are are basically a hashable label:
http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols

Your solution does seem slightly gimmicky, but it does give you some
benefit of runtime key checking... any string would be accepted in
code, but only defined objects will.

An important point is that everything is an object in Python, and thus
can become a key (or value for that matter) in a dictionary.

If you were interested in exploring the symbol thing further in
Python, it looks like there is an implementation in a similar manner
(using class instances though, instead of class objects) in the cheese
shop:

http://pypi.python.org/pypi/SymbolType

Cheers,
Eric

On Fri, Aug 12, 2011 at 12:39 PM, Mark Erbaugh <mark at microenh.com> wrote:
> I'm using a dict to store some parameters. I accidentally initialized the dict with {min:0} rather than {'min':0}, but the former worked as the built-in function min is hashable and thus suitable as a key. This saves me from having to type quotes in when I retrieve the value  (i.e. info[min] rather than info['min']). I'm thinking it's marginally faster as there's no string processing involved.  The only downside I can come up with is that the min function is not being used as intended and it could be confusing.
>
> The same principle allows you to create objects to be used as dictionary keys to make the [key] lookup syntax cleaner.
>
> What do people think about this?
>
> class A: pass
> class B: pass
>
> d = {A:'value for A', B:'value for B'}
>
> Mark
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>


More information about the CentralOH mailing list