[Python-Dev] Non implementation dependent access to calling scope

"Martin v. Löwis" martin at v.loewis.de
Sat Mar 10 13:57:42 CET 2007

Michael Foord schrieb:
> Hello all,
> I realise that this may be more relevant to Python ideas, in which case 
> feel free to ignore this (and my apologies).
> I occasionally see code looking (something) like :
> calling_scope = sys._getframe(1).f_globals['__name__']
> This looks and smells like a hack (not least because of the warning in 
> the documentation about _getframe), 

Right. This should some helper functions in inspect (which currently
aren't there).

> plus stack frames are an 
> implementation detail so this code is broken on IronPython.

I don't think there is much you can do about this. Local variables are 
also an implementation detail.

> It would be great to have a specified way to obtain [a read only view on 
> (?)] the locals and globals from the calling scope. Perhaps built in 
> functions ?

Please, no builtin functions.

> If they were specified then the IronPython guys would have 
> to implement it for us. B-)

I doubt it. If users of IronPython would want that badly enough, it
would be there. sys._getframe has been in CPython for a while, yet
it (apparently) is unavailable in IronPython. I would expect that
implementing what you propose would similar in effort to implementing

> I realise that this can allow bad some bad programming patterns, but 
> there are times when it can be very useful.

Users who want it can already do it, in CPython. The example you gave
isn't even about locals, but the caller's *globals*. I would guess
that there is already a way in IronPython to get at these, given that
.NET also needs to support stack walks in various places.


More information about the Python-Dev mailing list