1

I am trying to access a global variable which was defined in my main Python file from inside an object instance. I have read some other questions on the topic and I learned I need to use the global keyword inside my class method first.

However, even so, my code does not seem to work:

from secondclass import SecondClass

somelist = [1,2,3]
obj = SecondClass()

obj.mainmethod()

And here is my other file containing secondclass:

class SecondClass():
  
  def mainmethod(self):
    global somelist
    print (somelist)

Even through I am using the global keyword, Python still gives me error:

NameError: name 'somelist' is not defined

Why is that?

1
  • In Python, global is local to the module. It is not global worldwide. If your class needs that list, then you should pass it to the constructor. Commented Apr 27, 2022 at 5:53

1 Answer 1

2

global is scoped to the same module.

You have multiple options to solve this, among them:

  • Pass the variable to the class and use self.attribute.
  • Pass the variable to the method.
  • Create a module holding the global, such as globals.py and import it from both sides.
  • Inject the global using import secondclass; secondclass.somelist = [1,2,3]

And plenty of other solutions.

Personally, I'd go for the first or second any day of the week.

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

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.