No macros in Python
Ben Leslie
benno at sesgroup.net
Sun Dec 15 20:07:44 EST 2002
On Mon, 16 Dec 2002, Courageous wrote:
>
> >Hmm, that's called "unhygienic macros" and is widely considered a bad
> >idea.
>
> I know what unhygienic macros are. One way around this flaw might be
> to create a context in which the enclosing namespace is made available
> but not the default. This would allow a specific and deliberate
> manipulation of the enclosing namespace, but avoid accidental ones.
> I'm just sort of thinking out loud here.
>
> Of course, for all I know, there's a way to grab the stack and get
> the invokers locals already, if you really insist on this. Is there?
>
Use the inspect module. Example:
"""
import inspect
def callee():
caller_frame = inspect.currentframe().f_back
print caller_frame.f_code.co_name
print caller_frame.f_locals
def caller():
caller_local_1 = 3
callee()
def caller2():
x = 12
callee()
caller()
caller2()
"""
Output:
caller
{'caller_local_1': 3}
caller2
{'x': 12}
More information about the Python-list
mailing list