Proposed PEP for a Conditional Expression

Alex Martelli aleax at aleax.it
Wed Sep 12 09:29:23 EDT 2001


"Gareth McCaughan" <Gareth.McCaughan at pobox.com> wrote in message
news:slrn9pt5k6.18fr.Gareth.McCaughan at g.local...
> Terry Reedy wrote:
>
> [Christian Tanzer:]
> > > Conditional expressions provide some nice benefits totally
> > > unrelated to lambdas.
> > > One example: with a trivial class, one can put expressions into
> > > format directives, like
> > >   "Found %(number)d error%(if number == 1 : '' else : 's')s" % trivial
> >
> > Python does not evaluate expressions inside strings and I do not
> > expect it ever will.
>
> class Trivial:
>   def __getitem__(self, key):
>     return eval(key, globals(), locals())
>
> "foo %(1+2+3)s bar" % Trivial()    ===> "foo 6 bar"
>
> Giving it access to the caller's local variables
> isn't quite so easy.

It ain't *CLEAN*, but then the whole caboodle is hardly
spotless anyway.  But *easy*, it IS:

class Quadrivial:
    def __init__(self):
        import sys
        caller = sys._getframe(1)
        self.ll = caller.f_locals
        self.gg = caller.f_globals
    def __getitem__(self, key):
        return eval(key, self.gg, self.ll)

a=23
b=42
def f():
    b=97
    c=74
    print ">> %(b+100)s %(a*10)s %(c+1000)s"%Quadrivial()

f()

will print

>> 197 230 1074

just as expected/desired.


On whether the Python language should be changed to
*encourage* the use of such techniques, respondant
says no further.  (but, it IS fun:-).


Alex






More information about the Python-list mailing list