Variable scope and caller

Mike Meyer mwm at mired.org
Mon Dec 16 01:13:18 EST 2002


elechak at bigfoot.com (Erik Lechak) writes:

> This is what it would look like when it works:
> 
>    a = pstring("hello $b")
>    b = "erik"
>    print a
>    b = "moon"
>    print a
> 
> OUTPUT
> hello erik
> hello moon
> 
> 
> In other words the __str__ function will find the local variables (and
> globals) then do a replace on the elements of the string starting with
> '$'.  This is one of the main features of perl and I would like to
> prove it to myself that python can handle it without resorting to all
> kinds of trickery.

I don't think perl will do what you're asking for there. Unless I'm
badly mistaken, the value passed to pstring when you do the assignment
to a will be "hello ". The substring "$b" will be expanded at the time
of the assignment to a, not during the print statements.

I haven't figured out exactly what you want, and think it's one of two
things.

One is the Shell-like expansion of variables in a string. The closest
you can get to that is %-expansion with a dictionary:

        a = "hello %(b)s"
        b = "erik"
        print a % globals()
        b = "moon"
        print a % globals()

will give you the output you asked for.

Now, if what you really want is dynamic binding, you're out of
luck. That would be making something like this work:

def f():
    print a

def test():
    a = 1
    f()
    a = 2
    f()

and having it print 1 then 2. While this is a nice feature in a
scripting language, it has no business in a serious programming
language. I've seen the claim that the first implementation of dynamic
binding was a bug. Dynamic binding is the source of enough problems
that I'm willing to believe it.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list