[visionegg] Re: Confused about variable scope

  • From: jascha swisher <swisher@xxxxxxxxxxx>
  • To: visionegg@xxxxxxxxxxxxx
  • Date: Fri, 2 Apr 2004 09:21:07 -0500 (EST)

Hi Alex -

Yeah, this particular bit of python confused me at first, too. ;) The 
short story is that the global keyword is only needed if you are going to 
be *assigning* to a global variable within a local code block. If you are 
just referencing a variable, without assignment, then global isn't 
needed. In general, python first attempts to resolve variable names within 
the local scope, then searches the enclosing scope if the name is not 
bound locally.

In your example, both duration_per_image and texture_object are defined in 
the top-level code block, one level up from the function. Since they're 
not being assigned to within the function, they don't need to be 
explicitly declared global. Python looks for them in the function body, 
doesn't find them, then locates them in the enclosing scope. Thus, no 
error. ;)

This is explained in a little more detail here:
http://mail.python.org/pipermail/tutor/2003-March/021138.html

Hope this helps...
  -- jascha

On Thu, 1 Apr 2004, Alex Wade wrote:

> I realise that this is probably more of a python thing than
> a visionegg problem but...
> 
> I don't understand the way that variables scope is resolved
> in, say, a controller function. Here, from the
> image_sequence_fast.py example there's a bit of code that
> reads:
> .....
> 
> def put_image(t):
>     i = int(t/duration_per_image) # choose image
>     texture_object.put_sub_image( image_list[i] )
>     
> p.add_controller(None,None,FunctionController(during_go_func=put_image))
> .....
> 
> Nothing has been declared as global. So how does
> 'put_image' know what, say, duration_per_image or
> texture_object are? 
> 
> What am I missing? 
> 
> thanks in advance...
> alex

======================================
The Vision Egg mailing list
Archives: //www.freelists.org/archives/visionegg
Website: http://www.visionegg.org/mailinglist.html

Other related posts: