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?

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
user2015567
  • 13
  • 1
  • 1
  • 3

2 Answers2

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!
Frxstrem
  • 38,761
  • 9
  • 79
  • 119
3

I recommend the following:

lib.py

def test():
    return "Hello!"

test.py

from lib import *
var = test()
print(var)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • 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? – user2015567 May 26 '15 at 22:40
  • Okay, I tested it, turns out your solution still works! Thank you! – user2015567 May 26 '15 at 22:52