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?

4
  • 3
    Firstly you can’t do this because you have mutual imports. Secondly once you have imported a symbol, you can never tell if it gets reassigned to something else. Commented Aug 28, 2020 at 21:44
  • 2
    Circular import. Once you get rid of that it will work. Commented Aug 28, 2020 at 22:08
  • whart do u mean by my_var: int ? Commented Aug 28, 2020 at 22:17
  • @Cyber-Tech: They're called type hints. Commented Aug 28, 2020 at 22:25

2 Answers 2

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.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.