I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don’t like it).. Besides that, I also noticed that when I have code like this
def some_function():
foo.some_method()
# some other code
if __name__ == '__main__' :
foo = Some_Object()
some_function()
even though I don’t pass in foo into some_function(), but some_function is still able to manipulate foo (??!). I don’t quite like this although it is somewhat similar to Javascript closure (?). I would like to know whether it is possible to stop some_function() from accessing foo if foo is not passed in as a function argument? Or this is the preferred way in python??! (I’m using python 2.5 under ubuntu hardy at the moment)
That script has really serious issues with style and organization — for example, if somebody imports it they have to somehow divine the fact that they have to set
thescript.footo an instance ofSome_Objectbefore callingsome_function… yeurgh!-)It’s unfortunate that you’re having to learn Python from a badly written script, but I’m not sure I understand your question. Variable scope in Python is locals (including arguments), nonlocals (i.e., locals of surrounding functions, for nested functions), globals, builtins.
Is what you want to stop access to globals?
some_function.func_globalsis read-only, but you could make a new function with empty globals:now calling
f()will given an exceptionNameError: global name 'foo' is not defined. You could set this back in the module with the namesome_function, or even do it systematically via a decorator, e.g.:this will guarantee the exception happens whenever
some_functionis called. I’m not clear on what benefit you expect to derive from that, though. Maybe you can clarify…?