2

I am trying to import variables from another module. My wish is to use the "import module" way not the "from x import y" way. The import line works, but I get an error when trying to print variables from the source module.

I have an empty init.py file; All files init, module1 and module2 are in the same folder. The folder is seen in sys.path. Using from x import y works. I wanna use just import module. What am I missing?

module1.py:

X=8 List=[8,2,9] ListOfStrings=["Champa","Lampa", "Dampa"] All=[X, List, ListOfStrings, String] print(All)\ 

module2.py:

import module1 import sys for p in sys.path: print(p) print(X) 

module1 is run but X shows as not defined.

Result:

[8, [8, 2, 9], ['Champa', 'Lampa', 'Dampa'], 'This is a string'] theactualpath\Desktop\Work Excercises\py_test Traceback (most recent call last): File "theactualpath\Desktop\Work Excercises\py_test\module2.py", line 6, in <module> print(X) NameError: name 'X' is not defined [Finished in 0.1s with exit code 1] [shell_cmd: python -u "theactualpath\Desktop\Work\Excercises\py_test\module2.py"] [dir: theactualpath\Desktop\Work Excercises\py_test] [path: various paths from my computer, not the current working folder thou] 
2
  • you have not imported module1 Commented May 6, 2019 at 8:34
  • @Netwave I did, sorry I had a problem formatting the question here and the first line did not show up. Commented May 6, 2019 at 8:37

3 Answers 3

1

You have two alternatives.

Reference the module1 namespace:

import module1 ... print(module1.X) 

Bring everything (or just whatever you need) from module1 into your module2 namespace:

from module1 import * # or just import whatever you need: from module1 import X ... print(X) 
Sign up to request clarification or add additional context in comments.

Comments

0

Hello and welcome to StackOverflow.

After importing the module import module1, the variable X is bound to the module's namespace, thus you have to replace

print (X) 

with

print (module1.X) 

Your first example (print (X)) would print the variable X from the current file and not from the module.

1 Comment

thanks for the welcome and clarifications! glad to be here
0

Using print(X) is wrong. You must use print(module1.X)

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.