String changing on the fly
elie at flashmail.com
Thu Oct 21 09:38:07 CEST 2004
aleaxit at yahoo.com (Alex Martelli) wrote in message news:<1glzcvj.5uv1lg12ypgy2N%aleaxit at yahoo.com>...
> Eli Daniel <elie at flashmail.com> wrote:
> > Hi,
> > I'm new to Python. Can you please tell me if the following is
> > possible.
> > My users are using other scripting launguage to write scripts. They
> > are used to write somthing like (keeping it simple)
> > T = 100
> > do_action ('It cost $T dollars')
> > where the above syntax ('It cost $T dollars') is interperted as ('It
> > cost 100 dollars').
> > I saw on way of doing it by using 'it cost '+ str(T) + ' dollars'.
> > But trying to keep it backward compatible, is there a way for the
> > function do_action, which resides in a class in a seperate file, to
> > take the original string (with the '$T') and replace it with the value
> > of T?
> As others have said, you need to pass do_action the dictionary of the
> local variables of the function (or module's body) from which you're
> calling it: do_action('it cost $T dollars', vars()). If you don't pass
> this argument explicitly it IS possible for do_action to recover it by
> black magic, but that would be very bad practice.
> Apart from this, your best bet might be to upgrade to 2.4 (the current
> beta appears quite good), which offers exactly this functionality in the
> string.Template class. Otherwise, see how string.py does it (in the 2.4
> standard library) and copy the solution. But reusing the solution
> directly is much preferable, and for that you need 2.4.
Thank you all.
I've written a solution which sends that vars on every function call
as suggested (do_action('it cost $T dollars', vars()) which works
I've spent some time trying to avoid sending the vars (before I saw
the previous post) with no much success (I've tried all kind of
imports which resulted in some weird issues for a new guy like me).
I'll try the beta, if it solves the problem that's great and if not
the above solution is good as well.
The previous language was TCL, not perl, although I've written T=100
(but also wrote 'keeping it simple').
More information about the Python-list