[Tutor] parsing chemical formula

Christian Tismer tismer@appliedbiometrics.com
Tue, 30 Mar 1999 15:17:40 +0200


Martijn Faassen wrote:
> 
> Christian Tismer wrote:
> >
> > Tim Peters wrote:
> > ...
> >
> > > NAME, NUM, LPAREN, RPAREN, EOS = range(5)
> >
> > As I see this idiom of creating ENUM-alike constants
> > appear again (see doctest), this deserves an entry in
> > some howto. Tim, when did you start using it?
> > Very elegant.
> 
> It's a neat idiom. I'm not sure where I got it from (I've used it too),
> but I recall a while back I was pondering the problem. You see, I hate
> counting, and one needs to *count* to do this trick with range. C's
> 'enum' doesn't have this problem. So I tried to figure out an elegant
> way to do something like:
> 
> enum(NAME, NUM, LPAREN, RPAREN, EOS)
> 
> but couldn't come up with anything that worked well. The main problem is
> of course that NAME etc simply aren't defined, so you get an exception.
> You can catch that exception of course, and then define, but so far
> that's still a kludge.
> 
> Perhaps: enum('NAME', 'NUM', 'LPAREN', 'RPAREN', 'EOS') could
> work..still, that is too much typing. :)
> 
> Of course this doesn't belong on tutor but in the newsgroup, really, but
> I felt so much mental exertion on my part deserved some mention
> somewhere, and this was a good opportunity. :)

:-))

Well, how 'bout this? 
You can even save to type those ugly commas:

>>> def enum(tokens, base=0):
... 	import string
... 	lis = string.split(tokens)
... 	g = globals()
... 	for i in range(len(lis)):
... 	    g[lis[i]] = i+base
... 
>>> enum("ONE TWO THREE", 1)
>>> ONE, TWO, THREE
(1, 2, 3)
>>> 

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer@appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home