[Numpy-discussion] simple python question on what happens when functions are declared

Robert Kern robert.kern at gmail.com
Wed Nov 19 18:39:08 EST 2008


On Wed, Nov 19, 2008 at 17:30, Frank Lagor <dfranci at seas.upenn.edu> wrote:
> Hi,
>
> Can someone please explain what happens here:
>
> In testfile.py:
>
> x = 5
> def arbFunc():
>    print x

You get an UnboundLocalError here.

>    del x

During the compilation process, Python sees this statement and assumes
that you meant 'x' to be local to this function. Otherwise "del x" has
no meaning. A del statement inside a function cannot affect the global
namespace without the statement "global x" at the top of the function.
I *don't* recommend using the global statement in order to do this.
Acquire the resource inside the function, then it will go away when
you return from the function. If you need to pass it to other
functions, pass it as an argument.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list