I'm trying to import a variable (name) from the main.py
file into another file to use for a function
# main.py
import Untitled2 as U
name = input("Type in your name: ")
U.func()
# Untitiled2
def func():
from main import name
print(f'Hello {name}')
I expected the code would return:
Type in your name:
someone # users input
Hello someone
But instead it returned:
Type in your name:
someone #users input
Type in your name:
someone #users input
Hello name
Hello name
When the function was called it re-started the main.py
file which then asked again for a user input.
It also repeated the function twice (I think it's because it was called twice; once during start and once again during the restart)
If I put the import statement before defining func()
it returns an AttributeError:
Traceback (most recent call last):
File "main.py", line 3, in <module>
import Untitled2 as U
File "/home/repl/82b3a5f0-5457-4eb4-8f42-814593a9a85d/Untitled2.py", line 1, in <module>
from main import name
File "/home/repl/82b3a5f0-5457-4eb4-8f42-814593a9a85d/main.py", line 4, in <module>
U.func()
AttributeError: partially initialized module 'Untitled2' has no attribute 'func' (most
likely due to a circular import)
If I call the function twice:
# main.py
import Untitled2 as U
U.func()
name = input("Type in your name: ")
U.func()
It returns a NameError:
Traceback (most recent call last):
File "main.py", line 4, in <module>
U.func()
File "/home/repl/f94e5764-008a-48d2-b77d-2c539d2b6a62/Untitled2.py", line 2, in func
print(f'Hello {name}')
NameError: name 'name' is not defined
How do I make the function get the variable (name) from main.py
without main.py
restarting