[Tutor] Getting name scope

Bernard Lebel 3dbernard at gmail.com
Thu Oct 6 04:15:13 CEST 2005


Thanks for the answer.

I have to confess this question is driven only by curiosity, I was not
even hoping to get such a function. I was reading some stuff about the
scopes in JScript and somehow this question arose in my mind.

For the record, the tutorial I am watching said that a name exists
*only* inside a block, wich is a local scope itself. So that statement
defied my experience with JScript so I wanted to put it to the test:

(this is JScript code ran into a 3D application that embeds Python,
JScript and few other activeX-capable langages).


var oSel = selection(0);

if ( oSel.type == 'polymsh' )
{
	var oMesh = oSel;
}

logmessage( oMesh.name );

//Output
//INFO : sphere



Then I was curious if it would have been the same in Python (I knew it
was not, but tested it nonetheless):

oSel = Application.selection(0)

if oSel.type == 'polymsh': oMesh = oSel

Application.logmessage( oMesh.name )

#Output
#INFO : sphere



So then the question arised if it was possible in Python to know to
what scope a name belongs. I don't know any use for this, but I just
wanted to know it was possible.


Thanks!
Bernard




On 10/5/05, Kent Johnson <kent37 at tds.net> wrote:
> 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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list