module import: NameError: name is not defined

后端 未结 3 398
一个人的身影
一个人的身影 2021-01-23 19:08

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 \"bui         


        
相关标签:
3条回答
  • 2021-01-23 19:37

    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

    0 讨论(0)
  • 2021-01-23 19:38

    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

    0 讨论(0)
  • 2021-01-23 19:42

    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.

    0 讨论(0)
提交回复
热议问题