module import: NameError: name is not defined

2019-03-07 09:43发布

How do I define the function in the importer so that it is visible inside imported? I tried this

importer.py is

def build():
    print "building"

build()

import imported

Whereby, imported.py is simply

build()

Yet, this fails

building
Traceback (most recent call last):
  File "C:\Users\valentin\Desktop\projects\maxim\miniGP\b01\evaluator\importer.py", line 6, in <module>
    import imported
  File "C:\Users\valentin\Desktop\projects\maxim\miniGP\b01\evaluator\imported.py", line 1, in <module>
    build()
NameError: name 'build' is not defined

Update After I have got the response to make the circular import, so that import and imported depend on each other, I feel that I need to make clear that this is not always good. My purpose is to specify some common strategy in the imported module. It will use some user-defined functions, e.g. build. User defines the necessary function(s) and calls the strategy. The point is that the shared strategy must not depend on specific user definitions. I believe that in place of import, I need something like evaluate(imported.py), which I believe is a basic function in any script language, including Python. irc://freenode/python insists that I must use import but I do not understand how.

3条回答
够拽才男人
2楼-- · 2019-03-07 10:29

Imports are not includes: they are idempotent and should always be at the top of a module.

There is no circularity; once import foo is seen, further instances of import foo will not load the module again.

You are getting the NameError because in the context of imported.py, there is no name build, it is known as importer.build().

I have no idea what you are trying to do with code as oddly structured as that.

查看更多
We Are One
3楼-- · 2019-03-07 10:32

importer.py

def build():
   print("building")

build() #this extra call will print "building" once more.

imported.py

from importer import build
build()

Note that both importer.py and imported.py must be in same directory. I hope this solve your problem

查看更多
别忘想泡老子
4楼-- · 2019-03-07 10:41

I know that this is a blasphemy but the thing that allows to import a module without tying the imported with importer is easily available in Python as a script language. You can always evaluate a file with execfile

查看更多
登录 后发表回答