NB: More on Classes and Globals

Class and Globals

We experiment to see if classes can see the globals of their surrounding environment.

We already know that functions can.

class Test:
    
    # x has not been declared within the class 
    # or any of its methods
    
    def static_test():
        print(x)
        
    def method_test(self):
        print(x)
x = 5
try:
    Test.static_test()
except NameError as e:
    print(e)
5
t = Test()
try:
    t.method_test()
except NameError as e:
    print(e)
5

So, global variables are also visible within classes.

The class can see the globals, even though x was defined after the class definition.

But what about imported classes and functions?

Try with Imports

Now let’s see how scope works with import.

Here is the code contained by the file test.py:

y = 15

def imported_function_test():
    print(x)

def imported_function_test_y():
    print(y)
    
class ImportedTest:
    
    def imported_static_test():
        print(x)
    
    def imported_method_test(self):
        print(x)
        
    def imported_static_test_y():
        print(y)
    
    def imported_method_test_y(self):
        print(y)

Now we import the module and all of its defined functions and classes.

from test import *

Imported Function

Now let’s see if x is in any way visible to module.

try:
    imported_function_test()
except NameError as e:
    print(e)
name 'x' is not defined
try:
    imported_function_test_y()
except NameError as e:
    print(e)
15

Imported Static Method

try:
    ImportedTest.imported_static_test()
except NameError as e:
    print(e)
name 'x' is not defined
try:
    ImportedTest.imported_static_test_y()
except NameError as e:
    print(e)
15

Imported Instance Method

t2 = ImportedTest()
try:
    t2.imported_method_test()
except NameError as e:
    print(e)
name 'x' is not defined
try:
    t2.imported_method_test_y()
except NameError as e:
    print(e)
15

Conclusion

The global context of a class or function is the module, i.e. file, in which it is defined,
not in which it is called.