[Python-ideas] List Revolution
Massimo Di Pierro
massimo.dipierro at gmail.com
Sat Sep 10 21:14:13 CEST 2011
Not to open a can of worms but why not use eval in this example?
It is faster. It is 5x more compact. It allows me to take advantage of the Python parser instead of reinventing the wheel. It is less error prone and easier to understand. It is a python keyword.
# with eval
if not re.compile('^[\*\+\(\)\d]+$').match(name): raise AttributeError
try: number = eval(name)
except: raise AttributeError
# without eval
tokenizer = re.compile('\+|\(\+|\(|\)|\*|[\d]+')
stack = [0]
while name:
token = tokenizer.match(name)
if not token: raise AttributeError
elif token.group() in ('(','(+'): stack.append(0)
elif token.group().isdigit(): stack.append(int(token.group()))
elif token.group() in ')+' and len(stack)>1: stack[-2:]=[stack[-1]+stack[-2]]
elif token.group()=='*':
name = name[1:]
token = tokenizer.match(name)
if not token or not token.group().isdigit(): raise AttrbuteError
stack[-1:]=[stack[-1]*int(token.group())]
name = name[token.end():]
number = sum(stack)
Massimo
On Sep 10, 2011, at 1:00 PM, Guido van Rossum wrote:
> I thought we were all just having a little bit of fun with what's
> obviously the least-likely-to-be-accepted proposal to have hit
> python-ideas in a long time; and now I see serious questions about it
> on Twitter and Quora... Time to start adding smileys to all posts! :-)
>
> (Though seriously, Massimo, you should be able to implement the same
> idea without using eval() at all.)
>
> --Guido
More information about the Python-ideas
mailing list