2

I am trying to make a change to a global variable across classes. Here is my code:

file main.py

import class2

class first:
    def changeA(self):
        global a
        print a
        a += 2
        print a

test0 = first()
test1 = class2.second()
test2 = first()
test3 = class2.second()
test0.changeA()
test1.changeA()
test2.changeA()
test3.changeA()

file class2.py

a = 1

class second:
    def changeA(self):
        global a
        print a
        a += 1
        print a

But it returns an error: global name 'a' is not defined. Is there any proper way to access and change a global variable across files in python? Thanks in advance

4
  • 3
    Why are you using global variables? Commented Nov 11, 2014 at 6:54
  • possible duplicate of Python global variables don't seem to work across modules Commented Nov 11, 2014 at 7:20
  • @IanAuld: because I want to change it across some python files. I still don't find another way to do that Commented Nov 11, 2014 at 8:04
  • @ferryard If you have a variable/value that you find yourself needing across several files you most likely have a design problem. You may want to reevaluate how you have your app broken up. You may want to consider using a config file/dictionary or refactoring your code to eliminate the need for passing this value around or just importing it if it's a constant. Commented Nov 11, 2014 at 19:40

2 Answers 2

6

Global variables don't exist in python.

The global statement is really a misnomed statement. What it means is that the variable is a module's variable. There is no such a thing as a global namespace in python.

If you want to modify a variable from multiple modules you must set it as an attribute:

import module

module.variable = value

Doing a simple assignment will simply create or modify a module's variable. The code

from module import variable

variable = value

simply shadows the value of variable imported from module creating a new binding with that identifier but module's variable value will not be changed.

In summary: no there is no way to achieve exactly what you want (although what you want would be a bad practice anyway, and you should try to use a different solution).

Sign up to request clarification or add additional context in comments.

Comments

1

global variables are evil: avoid them!

It is much better to use a 'static' (in C++ terms) member variable, such as:

from class2 import second
class first:
    def changeA(self):
        print second.a
        second.a += 2
        print second.a

And:

class second:
    a = 1
    def changeA(self):
        print second.a
        second.a += 2
        print second.a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.