问题
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