Search code examples
pythonfunctionpython-importimporterror

Python variable declaration and function error


I have an question about Python.

I want to use an variable inside an function but I get this error:

NameError: name 'BP' is not defined

Here is my code:

# File 1 test.py:
from importlib import import_module

def test():
    print(BP)
    print(BP["test2"].d)

if __name__ == "__main__":
    BP: (dict) = {}
    BP.update({"test2": import_module(".test2", "test_folder")})



# File 2 file2.py in test_folder:
from test import test

d: (dict) = {"Hello": "World"}

print("hi")
test()

So my question is: why is this not working?


Solution

  • Regarding:

    if __name__ == "__main__":
    

    That's only true if you actually run the test.py file, not when you just import it, as you do from file2.py. In the latter case, there is no code running to bind the BP variable to an object, so calling test will complain about it.