On 26 Mar 2005 22:51:14 -0800, [EMAIL PROTECTED] (Oren
Tirosh) wrote:

>Ron_Adam <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
>> 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

Cool!  I haven't played with decorators yet. :)

I noticed the 'new' module is depreciated. It referred me to call the
object type directly instead.  So this is probably the better way.

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

@noglobals
def a():
    global x
    try: x
    except: x=0
    x += 1
    return x

x = 5
for n in range(10):
    print a()
print x         # x is still 5


So this is another, but longer, way to do a generator. 


>>> print type(a).__doc__
function(code, globals[, name[, argdefs[, closure]]])

Create a function object from a code object and a dictionary.
The optional name string overrides the name from the code object.
The optional argdefs tuple specifies the default argument values.
The optional closure tuple supplies the bindings for free variables.
>>> 

What are 'free variables'?

And is there a way to directly read what names in a function are set
with the global statement? (Other than looking at the monitor. ;)

Ron_Adam


  


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to