-1

I have 2 differents files. The first one, defines a lot of class:

# File 1:

class Class1:

class Class2:

#...

Those classes uses some variables that are define as global.

# File 1:

class Class1:
    def __init__(self, var1):
        global glob_variable_1

        # Other stuff
class Class2:

#...

In the file 2, I import all the class from the first file and then use them. In this main part of this file, I define the global variables.

# File 2
from File1 import Class1, Class2

if __name__ == '__main__':
    global glob_variable_1

    glob_variable_1 = 10
    # Other stuff
    Class1(var1)

I get the error NameError: name 'glob_variable_1' is not defined.. I suppose it's a problem of namespace and scope, but I don't really understand how it works. Can someone give me a hand? Thanks.

Mathieu
  • 5,410
  • 6
  • 28
  • 55
  • When and how to you attempt to access `glob_variable_1`? I get `NameError: name 'var1' is not defined` from your code. – cdarke Feb 13 '19 at 15:44
  • This might be a relevant thread: https://stackoverflow.com/questions/15959534/visibility-of-global-variables-in-imported-modules – r.ook Feb 13 '19 at 16:08
  • @cdarke my code being 2K+ lines, I just gave an idea of how it was structured: 2 files, one in which I have the class define and the second which importants those class. Inside the first file, in the class, the variable glob_variable_1 is called (thus the global glob_variable_1 at the beginning of the `__init__` method). However, those global variable are initialized in the second file. – Mathieu Feb 13 '19 at 17:04
  • @Idlehands I'll have a look, thank you. – Mathieu Feb 13 '19 at 17:05
  • Sharing variables between modules is a flawed design, there are better ways. Use an encapsulated function instead. – cdarke Feb 14 '19 at 18:05
  • @cdarke I agree and that's what I did in the end. – Mathieu Feb 15 '19 at 10:06

1 Answers1

1

You have two glob_variable_1 names, one in each namespace and you must decide which one to use:

# File 1:

# defined here, outside the class
glob_variable_1 = None   

class Class1:
    def __init__(self, var1):
        global glob_variable_1
        glob_variable_1 = 42

        # Other stuff
class Class2:
    pass

with:

# File 2
from File1 import Class1, Class2
import File1

if __name__ == '__main__':
    global glob_variable_1
    # Other stuff
    var1 = 1234
    obj = Class1(var1)

    glob_variable_1 = 666
    print(glob_variable_1)
    print(File1.glob_variable_1)

Gives:

666
42       

Far better than using a global variable across modules is to use a function to set/get in a class or a file.

cdarke
  • 42,728
  • 8
  • 80
  • 84