0

I have several files with functions which use one variable.

main.py

from functions import my_func

my_var: int

def main():
   my_var = 5
   my_func()

functions.py

from main import my_var

def my_func():
   print(my_var)

And it is not working. I understand that I can pass my_var in my_func() but is there any other method and, if so, how can I do this?

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

On line 2, you cannot import my_func from functions.py, as that requires to import my_var from main.py on the 1st line of funtions.py.

Zephyr
  • 11,891
  • 53
  • 45
  • 80
VÁP
  • 63
  • 1
  • 7
1

The problem here is that you're trying to interact with a local variable, so you have to use the keyword "global variable" inside the function before interacting with it. Another problem is the circular imports in Python (check this answer: Circular (or cyclic) imports in Python).

If you do import foo (inside bar.py) and import bar (inside foo.py), it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.

The problem is when instead you do from foo import abc (inside bar.py) and from bar import xyz (inside foo.py). Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.

R1ky68
  • 40
  • 1
  • 8