String changing on the fly

Dave Benjamin ramen at lackingtalent.com
Mon Oct 25 21:59:06 CEST 2004


In article <1gm04ht.e3wqjt19zaabaN%aleaxit at yahoo.com>, Alex Martelli wrote:
> Well, maybe not THAT clear, but hopefully scary enough.  The concept is:
> if you know what you're doing, we trust you, and we don't prevent you
> from doing what you judge NEEDS to be done, even though it requires
> black magic that reaches behind the scenes of the execution model,
> plucking a frame out of the call-stack and accessing its implementation
> detail 'f_locals' attribute -- "on your head be it";-).

This type of stack manipulation is much more common in Tcl, where it is used
to accomplish tasks as simple as passing an array to a function! The "black
magic" procedures in Tcl are "upvar" and "uplevel". Their use is discouraged
in most cases, as one might expect in any language, but they are useful in
implementing control structures.

One particularly nice implementation of string interpolation, done by
Ka-Ping Yee, is available here:

http://lfw.org/python/
(search for "string interpolation for Python")

It "hacks the stack" to find the calling environment's variables, and allows
many neat tricks like the following:

from Itpl import printpl
printpl("Here is a $string.")
printpl("Here is a $module.member.")
printpl("Here is an $object.member.")
printpl("Here is a $functioncall(with, arguments).")
printpl("Here is an ${arbitrary + expression}.")
printpl("Here is an $array[3] member.")
printpl("Here is a $dictionary['member'].")

I have used this successfully in a homebrew templating system for several
websites, and found that it offers just the right compromise between
convenience and flexibility. YMMV. ;)

Another, similar use of this "black magic" that I've done is to write a
function that works like PHP's "compact":

http://php.net/compact

If you've got a lot of dictionary construction and deconstruction to do,
this simple trick can save a lot of {'redundant': redundant,
'mapping': mapping} between locals and dictionaries.

(but of course it still feels dirty)

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
        "talking about music is like dancing about architecture."



More information about the Python-list mailing list