I have 2 py files in the same folder (IDE Pycharm):
module1.py contains:
def test_func():
return "test_func"
class test_class(object):
def __init__(self):
self._test = test_func()
driver.py contains:
from module1 import test_class
obj = test_class()
print obj._test
I was expecting the the driver.py to fail with as the class instantiation requires the test_func() to be in scope.
To my surprise it didn't fail. I am not sure why (in fact there are a few posts in Stack Overflow asking about how to make function globally available to be used inside of class).
Is there such thing as "closure" on function object?
What is the difference between my 'imaginary problem' and this SO question? create a global function in python
EDIT
As explained below, the SO question was to do with calling sys.exit. It has nothing to do with the function scope per say.
self._test = test_func()is run, Python looks first in the function namespace for the nametest_func, and failing to find it, looks to the next level -- the module namespace. There isn't really a closure involved, I don't think. Note also that the name is only resolved when__init__runs... not when it is defined.__init__.pyin the same folder. the driver.py specifically import only the class definition not the entire content of the file. How could python actually find the this function? otherwise there is never a need to import anything as long as they are in the same folder?driver.pyinstantiatestest_class,module1.pyis used to lookup names. It would be bizarre any other way. Imagine if you always needed to implement all supporting functions just to instantiate someone else's class.