0

Although the variable should be imported, I get "name X is not defined" exception.

main.py

from config import *
from utils import *
say_hello()

utils.py

from config import *
def say_hello():
    print(config_var)

config.py

from utils import *
config_var = "Hello"

Trying to run "main.py":

Traceback (most recent call last): File "main.py", line 3, in say_hello() File "C:\Users\utils.py", line 3, in say_hello print(config_var) NameError: name 'config_var' is not defined

What happened here? Why some_var is not accessible from utils.py?

  • 1
    In general, it is considered a bad idea to use `from module import *` syntax. Try to import what you need, and only what you need. Or, at the very least, simply do `import module` so that it's clear where the variables you use are coming from. – Calvin Godfrey Jan 16 '19 at 14:05
  • Besides the circular dependency issue, `import *` [is not considered](https://stackoverflow.com/a/2386740/2996101) a good practice. – raratiru Jan 16 '19 at 14:06

3 Answers3

0

You are importing config in util and util in config which will causing this error(create cross loop). remove from utils import * from config.py and then try this.

And in main.py you don't need to import the from config import * unless you are using variables from config directly in your main()

Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19
  • Let's assume I'm using variables/functions from config on both main.py and utils.py and that I need my utils.py functions on config.py file. What is this cross loop? Is there any Python reference to this issue? – user2290955 Jan 16 '19 at 14:09
  • No you can use import in two files which are importing from each other. At each import statement python goes in other file and it get another import statement there which goes in first file so that won't work – Amit Nanaware Jan 16 '19 at 14:12
0

you should also import config.config_var, since this variable belongs to that specific module

Michel Kluger
  • 164
  • 1
  • 6
0

You are creating to many import statements perhaps try the following below, but also you need to define a parameter in utils.py if you are passing a parameter through there.

In utils.py we require a parameter to be passed since you want to print out the appropriate value, In config.py you are defining a value. Then in main.py as discussed before using the wildcard operator "*" isn't entirely good in this situation then in order to call the respective functions you need to address them through their file name

In utils.py :

def say_hello(config_var):
    print(config_var)

In config.py

config_var = "Hello"

Then in main.py

import config as cn
import utils as ut
ut.say_hello(cn.config_var)

Check out this thread for how to write python modules as well How to write a Python module/package?