| Store | Cart

Turn of globals in a function?

From: Oren Tirosh <o...@REMOVETHIS1.hishome.net>
26 Mar 2005 22:51:14 -0800
Ron_Adam <radam2 at tampabay.rr.com> wrote in message news:<6qeb415iqqsor4biebk6rqj9g6jv3lpt55 at 4ax.com>...
> Is there a way to hide global names from a function or class?> > I want to be sure that a function doesn't use any global variables by> mistake.  So hiding them would force a name error in the case that I> omit an initialization step.  This might be a good way to quickly> catch some hard to find, but easy to fix, errors in large code blocks.

def noglobals(f):
.   import new
.   return new.function(
.       f.func_code, 
.       {'__builtins__':__builtins__},
.       f.func_name, 
.       f.func_defaults, 
.       f.func_closure
.   )

You can use it with the Python 2.4 @decorator syntax:

@noglobals
def a(...):
.   # code here

Doing this for a class is a little more work. You will need dig inside
to perform this treatment on each method separately and handle new and
old-style classes a bit differently.

Note that this kind of function may declare globals. They will be
persistent but private to the function.

  Oren

Recent Messages in this Thread
Ron_Adam Mar 26, 2005 08:01 pm
Michael Spencer Mar 26, 2005 08:18 pm
Bengt Richter Mar 26, 2005 09:02 pm
Ron_Adam Mar 27, 2005 02:49 am
Oren Tirosh Mar 27, 2005 06:51 am
Ron_Adam Mar 27, 2005 04:45 pm
Greg Ewing Mar 31, 2005 04:28 am
Ron_Adam Mar 31, 2005 05:31 pm
Ron_Adam Mar 27, 2005 02:13 am
Messages in this thread