1

I don't know how explain what I want do so I think with code example you can understand.

y.py

y = 0

import printy

printy.py

import y

print y

NameError: name 'y' is not defined

When I call scripts with import works perfect but I want to know how I can share variables.

y.py

import printy

printy.py

y = 0

print y

result = 0
3
  • 1
    possible duplicate of Importing variables from another file (python) Commented Jul 31, 2015 at 11:37
  • 1
    try: import printy; print printy.y or from printy import y; print y. Commented Jul 31, 2015 at 11:40
  • 1
    It's generally not a good idea to have two modules that import each other, so try to avoid that if you can. Do a search for "circular imports" for more info. Commented Jul 31, 2015 at 11:56

1 Answer 1

1

I don't know which is which file, (assuming each code block is a different file) it should work, and share variables if importing them works. Also, I would write it like this:

file y.py:

from printy import *

y = 0

file printy.py:

from y import *

print y

Also, both files have to already exist at time of running, and they have to saved into the same folder.

EDIT: If result = 0 is the output, then everything is working fine. Also, if this doesn't work, I'd do printy.print(y)

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

1 Comment

Also, if you want to do more complex code, it will work best to save the code, in file being retrieved, in a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.