1

I have two files:

lib.py

global var
def test():
    var = "Hello!"
    return

test.py

from lib import *
test()
print(var)

But despite having them in the same folder, when I run test.py, I get the following error:

Traceback (most recent call last):
  File "C:\Test\test.py", line 5, in <module>
    print(var)
NameError: name 'var' is not defined

How can I access this variable in a function in another file?

2
  • 4
    Instead of using globals, why not have that function return a value, which you can save? Commented May 26, 2015 at 22:22
  • You can't access the variables in functions, unless you return them or something. Commented May 26, 2015 at 22:30

2 Answers 2

5

You need to declare the variable as global in the scope which it is used, which in this case is the function test():

def test():
  global var
  var = "Hello!"

Note that the final return is not necessary, since it is implicit at the end of a function. Also, var is declared in the global scope of the module, so it won't be imported automatically by from lib import * since it's created after the module has been imported.

Returning var from the function is probably a better solution to use across modules:

def test():
  var = "Hello!"
  return var

var = test()
print(var) # Hello!
Sign up to request clarification or add additional context in comments.

Comments

3

I recommend the following:

lib.py

def test():
    return "Hello!"

test.py

from lib import *
var = test()
print(var)

2 Comments

Thank you for your help! I can see why you've done this, as it follows the intended use of variables much more closely. However, what I should have explained that the problem I outlined above is a simplified version. in one file, I have pygame code in a function such as: screen = pygame.display.set_mode((width, height)) And I am trying to access this by utilising it in another file: pygame.gfxdraw.aacircle(screen, 175, 130, 60, red_on) As such, am I correct in thinking that I could not use the return functionality to achieve this?
Okay, I tested it, turns out your solution still works! Thank you!

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.