On Tue, Feb 24, 2009 at 12:13 PM, Wyatt Baldwin <[email protected]> wrote: > > On Feb 24, 10:54 am, [email protected] wrote: >> * ** Accessing callers context from callee method** >> * >> >> when i call a method foo from another method func. can i access func context >> variables or locals() from foo >> so >> def func(): >> i=10 >> foo() >> >> in foo, can i access func's local variables on in this case i >> Thanks a lot > > May ask why you want to do this? There might be an easier way to > accomplish whatever is you're trying to do. > > I think it is possible, but not without doing some funky magic. You > might want to just use a class or pass local vars from func to foo. > Maybe foo(**locals())?
You can access the execution stack using the ``inspect`` module, or by raising a bogus exception and catching the traceback. However, this is justifiable only in very narrow circumstances, where a generic routine needs to do magic on a wide variety of callers, such as where the ``traceback`` module prints a stack trace, or the equivalent in GUI frameworks and debuggers. The rule of encapsulation argues that a function should operate only on its arguments. So you should pass everything it needs. foo(**locals()) can be paired with "def foo(**kw):" to get all the local variables in one step. However, if you want to modify data in the caller, you either need to put it in the return value, or pass a mutable argument (such as a list, dict, or instance) that the function can modify in place. Or if these are methods in a class, the method can modify 'self' attributes. -- Mike Orr <[email protected]> --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "pylons-discuss" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/pylons-discuss?hl=en -~----------~----~----~----~------~----~------~--~---
