Ipython notebook : Name error for Imported script function

China☆狼群 提交于 2019-12-14 03:27:03

问题


I have two scripts sources.py and nest.py. They are something like this

sources.py

import numpy as np
from nest import *

def make_source():
    #rest of the code

def detect():
    Nest = nest()
    Nest.fit() 

if __name__=='main':
    detect()

nest.py

import numpy as np
from sources import *

class nest(object):

    def _init_(self):
        self.source = make_source()

    def fit(self):
        #rest of the code

When I run the script like python sources.py It works fine.

But in the Ipython notebook environment if I do the following

In [1]: from sources import *

In [2]: detect()

I am getting the following error

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-e9c378341590> in <module>()
---->  detect()

C:\sources.pyc in detect()
--> 7 Nest = nest()

C:\nest.pyc in _init_()
--> 7 self.source = make_source()

NameError: global name 'make_source' is not defined

I am confused about why this is occurring. Can you give me an insight on how it is different in both cases and how to solve this ?


回答1:


The thing is that there is a difference between

import something

and

from something import *

concerning namespaces.

If you have recursive imports its better to never do "from something import *" or "import something as someotherthing"

You get a full explanation here:

Circular (or cyclic) imports in Python



来源:https://stackoverflow.com/questions/24778375/ipython-notebook-name-error-for-imported-script-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!