If __name__ == '__main__' ipython does not work

I find it difficult to get the trick if __name == '__main__' to work in IPython, Spyder. I tried every approach given in this thread: if __name__ == '__main__' in IPython

Here are my super simplified modules

Module1.py

 Class UnitTest(): print 'Mod1 UnitTest!' if __name__ == '__main__': UnitTest() 

Module2.py

 import Module1 Class UnitTest(): print 'Mod2 UnitTest!' if __name__ == '__main__': UnitTest() 

So, I run Module2.py, and I always see both Mod2 UnitTest and Mod1 UnitTest . They run in the IPython kernel. I want to show only the Mod2 UnitTest .

Any idea what's up?

+5
source share
1 answer

Well, I deleted this question earlier because of embarrassment, but could also share if any other newborn sees it.

I forgot to put the UnitTest line inside the __init__ method. Thus, the unit test was run every time the class was defined, and not when the object was created. The code should be:

Module1.py

 Class UnitTest(): def __init__(self): print 'Mod1 UnitTest!' if __name__ == '__main__': UnitTest() 

Module2.py

 import Module1 Class UnitTest(): def __init__(self): print 'Mod1 UnitTest!' if __name__ == '__main__': print 'Mod2 UnitTest!' 
+2
source

All Articles