#๐Ÿ”’ How to import variables from one python file to another

22 messages ยท Page 1 of 1 (latest)

limpid dock
#

I am working with python in vscode, connected to a repo in gitlab. I was under the impression that if I had 2 .py files and a __init__.py if at the top of one .py file I import the other, I can do from file1 import var1 and then I would have var1 accessible for use in my 2nd python file. This matches the stack overflow answer I looked up, but I am still getting an error NameError: name 'var1' is not defined. Any ideas as to what im doing wrong?

simple garnetBOT
#

@limpid dock

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

jaunty sage
#

Could you show the structure? With how you said it, the variable would be only accessible in the init file (so when you import the package name), not "in [your] 2nd python file".

Like file1.py, file2.py, __init__.py - to see the var1 in file2 you'd need to do the import in file2, not in init

limpid dock
#

sure hold on

#

all 3 files there

#

and the file structure

#

and then the error I get

#

oh sheesh

#

I think I fixed it

#

I didnt realize I had to run file1.py first

potent hamlet
limpid dock
#

oh yeah I never saved it either

potent hamlet
#

this white dot next to the file name means it has unsaved changes, right?

limpid dock
#

I just made all the files at once

#

and then I only ran file2

#

oh

#

maybe, I never noticed that

#

/close

#

!close

simple garnetBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.