简体   繁体   中英

import on Python doesn't work as expected

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?

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()

您还应该导入config.config_var,因为此变量属于该特定模块

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM