best way to have enum-like identifiers?

Peter Otten __peter__ at web.de
Wed Mar 12 04:52:40 EDT 2008


mh at pixar.com wrote:

> I currently have a 2-dim hash, indexed by two strings:
> 
>     template['py']['funcpre']
>     template['py']['funcpost']
>     ...
> 
> but I would prefer to have these indexed by constants of
> some kind, since this seems a bit more natural:
> 
>     template[py][funcpre]
>     template[py][funcpost]
>     ...
> 
> Currently I'm just putting this at the top of the file:
> 
>     py=1
>     funcpre=2
>     funcpost=3
>     ...
> but I'm curious if there's a better way of doing this,
> some kind of enum-like thing or somesuch.

A dictionary with a fixed set of keys is better spelt as a class, e. g.
instead of the inner dictionary you can use something like

class Hooks(object):
    def __init__(self, pre=None, post=None):
        self.pre = pre
        self.post = post

...
def before(): print "before"
def after(): print "after"

template["py"] = Hooks(before, after)

Peter



More information about the Python-list mailing list