Turn of globals in a function?

Ron_Adam radam2 at tampabay.rr.com
Sat Mar 26 21:13:20 EST 2005


On Sat, 26 Mar 2005 12:18:39 -0800, Michael Spencer
<mahs at telcopartners.com> wrote:

>Ron_Adam wrote:
>> 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.
>> 
>> Examples:
>> 
>> def a(x):
>>     # ...
>>     x = y         # x is assigned to global y unintentionally.
>>     # ...
>>     return x
>> 
>> def b(x):
>>     # hide globals somehow
>>     # ...
>>     x = y    # Cause a name error
>>     # ...
>>     return x
>> 
>> 
>> y = True
>> 
>> 
>>>>>a(False):
>> 
>> True
>> 
>> 
>>>>>b(False):
>> 
>> *** name error here ***
>> 
>> 
>> Ron_Adam
>> 
>>  
>For testing, you could simply execute the function in an empty dict:
>
>  >>> a = "I'm a"
>  >>> def test():
>  ...     print a
>  ...
>  >>> test()
>  I'm a
>  >>> exec test.func_code in {}
>  Traceback (most recent call last):
>    File "<input>", line 1, in ?
>    File "<input>", line 2, in test
>  NameError: global name 'a' is not defined
>  >>>

I didn't know you could do that. Interesting. :) 

I was hoping for something in line that could use with an assert
statement.  But this is good too, I'll have to play around with it a
bit. Thanks.

Ron


>This would get more complicated when you wanted to test calling with parameters, 
>so with a little more effort, you can create a new function where the globals 
>binding is to an empty dict:
>
>  >>> from types import FunctionType as function
>  >>> testtest = function(test.func_code, {})
>  >>> testtest()
>  Traceback (most recent call last):
>    File "<input>", line 1, in ?
>    File "<input>", line 2, in test
>  NameError: global name 'a' is not defined
>  >>>
>
>HTH
>
>Michael





More information about the Python-list mailing list