Ipython notebook : Name error for Imported script

2019-09-21 03:51发布

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条回答
你好瞎i
2楼-- · 2019-09-21 04:31

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

查看更多
登录 后发表回答