[Tutor] Getting name scope
Kent Johnson
kent37 at tds.net
Thu Oct 6 03:47:39 CEST 2005
Bernard Lebel wrote:
> Hello,
>
> Anyone know if it is possible to find out in what scope lies a name?
> For instance, let say I'm using a name in a function, but the name is
> actually in the global scope. I would like to know if this name was
> found in what scope. Is it possible at all?
Look for the name in locals() and globals()? But why do you care?
>>> a=1
>>> def scopeOf(name):
... x=3
... if name in locals():
... print name, 'is local'
... elif name in globals():
... print name, 'is global'
... else:
... print 'I don\'t know about', name
...
>>> scopeOf('x')
x is local
>>> scopeOf('a')
a is global
>>> scopeOf('foo')
I don't know about foo
This assumes that you actually know the name as a string. If you are trying to find out something about the variable in the calling scope then it is harder. There are hacks to find out the name of the variable in the calling scope but why?
Kent
More information about the Tutor
mailing list