OT: Reason to love the snake #332
Kragen Sitaker
kragen at pobox.com
Fri Feb 1 16:10:07 EST 2002
"Bruce Dykes" <bkd at graphnet.com> writes:
> Found on another board:
> > Actual code found in a production application:
> >
> > foreach (@list) {
> > /=/;
> > eval( qq( \$$` = "$'" ));
> > }
(Kids, this is not only an obscure way to do it, this is a stupid
thing to do. Uncle Mark says it could cost you thousands of dollars.
See http://perl.plover.com/varvarname.html for more on how dumb it
is.)
It translates directly into Python:
for _ in alist:
__ = _.find('=')
exec '%s = "%s"' % (_[:__], _[__+1:])
> > Now, that's obscure and overlong. You could just do:
> >
> > s/([^=]*?)=(.*)/\$$1="$2"/e for (@list);
The ? is superfluous there.
You can't do that in Python, fortunately. But you can do
map(lambda _:(lambda __,_=_:globals().update({_[:__]:_[__+1:]}))(_.find('=')),alist)
While longer and more verbose, this version is also more correct: it
will always update the globals instead of some random scope, it
correctly handles strings with embedded newlines and any kind of
quotes.
,_=_ is omittable in Pythons with nested scopes.
If we really want to bite it, we can do this:
import re
map(lambda _:(lambda (x,y),_=_:globals().update({_[:x]:_[y:]}))(re.search('=',_).span()),alist)
> > (Of course, no sane person would, but somebody managed to whip out the
> > first one without any apparent discomfort, either).
Such a person should not be writing production code.
More information about the Python-list
mailing list