Re: [Tutor] getting names from other funcs

Magnus Lycka magnus at thinkware.se
Tue Mar 23 17:25:03 EST 2004


> I can't recall how you get to a name in another function. Let's say 
> that i have a func called foo and it has certain variables and values 
> held in it that i want to grab and use in test():

The reason you can't recall it is that if you ever knew
how to do it, heavens angels have come down from the sky
and erased that particular section of your memory for
your own protection. I don't have a clue on how to do it.
Thank you angels!

Local variables are not supposed to be avilable from
outside a function, and they only have meaning in the
scope of that function, and only retain a value while
the function is executing.

There are several imaginary scenarios where it might
seem useful to know the values of local variables in
another function, but none works.

For instance, you might want to do something like this:

def f(p):
    x = p

def g():
    f(5)
    print f.x # This doesn't really work

g()
5

I.e. you want a local variable to remain after a function
call, and be able to access it in a convenient way from the
outside. First of all, this kind of coding would lead to
maintenance hell in real code which tends to be much more
complex than this. 

Just imagine a little change to the code.

def g():
    f(5)
    h() # Call another function.
    print f.x # This doesn't really work

If h in turn calls f (maybe indirectly) the value of f.x
will be different than you expected. Also, hanging on to
all local variables of old function calls will mean that
the programs will need much more memory.

A simple solution to this is to use a pass the values
you want to retain with the return statement as Karl
suggested, or to use a class instead of a function. Then
you have the tools to specifically decide what values
should persist between calls, and a simple way to 
distinguish between different incarnations of the class.

class F:
    def __init__(self, p):
        self.x = p

def g():
    f = F(5)
    print f.x # This will actually work!

g()
5


Another scenario is that you would like to be able to
access a local variable in a calling scope, like this:

def x():
    print y

def f():
    y = 5
    x()

f()
5

This is also bad, because it means that in order to be
able to call the function x you need to have a certain
set of local variables. What would be the point more than
to complicate code maintenance once again? The simple
solution here is to pass any value you want a function
to know in as a parameter.

If you feel that you will have a big burden passing so
many parameters all over the place, you have probably
divided your problem into pieces in a non-optimal way.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list