0

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

blackraven
  • 5,284
  • 7
  • 19
  • 45
  • I'd say, don't rely on using `import` to run code. Use functions instead. – quamrana Aug 11 '22 at 10:29
  • 2
    When you import a module (even with `from module import x`), all the code in that module gets executed. That is why it's generally a bad idea to have anything else then definitions in a module (e. g. calling a function, like you do here) outside of a `if __name__ == "__main__":` block. – Filip Müller Aug 11 '22 at 10:33
  • Check out [this question](https://stackoverflow.com/q/419163/19589534). If you read the whole answer, you'll understand. – Filip Müller Aug 11 '22 at 10:39

0 Answers0