[Tutor] Accessing callers context from callee method

Alan Gauld alan.gauld at btinternet.com
Wed Feb 25 00:41:12 CET 2009


<mobiledreamers at gmail.com> wrote

> when i call a method foo from another method func. can i access func 
> context
> variables or locals() from foo

Yes and there are several ways to do it, but nearly always this is a
bad idea. It will make foo almost totally unusable in any other
context since it will rely on the calling function having local 
variables
of a specific name (and possibly type). It is usually much better to
pass the variables into foo at call time. Or even to use global 
variables!

> def func():
>      i=10
>      foo()

How would you write foo? Would you require the variable in func()
to be called i? Or would you assign a referece to it using a 
dictionary
to access it?

Can you explain what you really want to do with this? What is the
motivation behind the request? There is probably a better
alternative...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list