pep 308: why doing (almost) nothing suffices
Walter Moreira
walterm at parque.homelinux.net
Mon Mar 10 11:37:14 EST 2003
On Sun, Mar 09, 2003 at 09:31:43PM -0700, Steven Taschuk wrote:
> Quoth Edward K. Ream:
> [...]
> > def choose_eval(cond, a, b): # warning: evals all arguments
> >
> > if cond: return eval(a)
> > else: return eval(b)
> >
> > Heavy duty stuff by my present bathtub standards. So to "delay" the
> > evaluation of an argument, just quote it. Wow--just like lithp. Example:
> >
> > choose_eval(a < b,"foo(a)","spam(b)")
>
> Hm. What about this little problem?
>
> >>> def optional_reverse(s, reverse=0):
> ... return choose_eval(reverse, 's.reverse()', 's')
> ...
> >>> optional_reverse('foo', 1)
> [...]
> NameError: name 's' is not defined
That problem may be fixed with the following addition to Edward's code:
import inspect
def choose_eval(cond, a, b):
globalns = globals()
localns = inspect.currentframe(1).f_locals
if cond:
return eval(a, globalns, localns)
else:
return eval(b, globalns, localns)
The example works well, then:
>>> def optional_upper(s, up=0):
... return choose_eval(up, 's.upper()', 's')
...
>>> optional_upper('foo', 1)
'FOO'
>>> optional_upper('foo', 0)
'foo'
But the main point surely is the efficiency if this is used in a loop.
Let's wait for Guido's pronouncement...
Walter
--
--------------
Walter Moreira <> Centro de Matematica <> Universidad de la Republica
email: walterm at cmat.edu.uy <> Home Page: http://www.cmat.edu.uy/~walterm
PGP: 0xF9833E99 B0CD B36A 77A7 E6ED 296C 147D 72B7 4B1E F983 3E99
PGP key: www.keyserver.net
More information about the Python-list
mailing list