Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Wildcard Import Vs Named Import

Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why. My file structure looks like this:

MainApp.py
res/
  __init__.py
  elements/
    __init__.py
    MainFrame.py

Inside of MainFrame.py I've defined a class named RPMWindow which extends wx.Frame.

In MainApp.py this works:

from res.elements.MainFrame import *

And this does not:

from res.elements.MainFrame import RPMWindow

I realize that the wild card import won't hurt anything, but I'm more interested in understanding why the named import is failing when the wild card succeeds.

When using the class name I get this traceback:

Traceback (most recent call last):
  File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 953, in <module>
    debugger.run(setup['file'], None, None)
  File "C:\myApps\eclipse\plugins\org.python.pydev.debug_1.5.6.2010033101\pysrc\pydevd.py", line 780, in run
    execfile(file, globals, locals) #execute the script
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
    from res.elements.MainFrame import RPMWindow
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MainFrame.py", line 2, in <module>
    from res.elements.MenuBar import MenuBarBuilder
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MenuBar.py", line 2, in <module>
    from MainApp import _, DataCache
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
    from res.elements.MainFrame import RPMWindow
ImportError: cannot import name RPMWindow

When using the wild card import I don't receive a traceback and my application opens.

like image 487
Dan Avatar asked Feb 27 '23 04:02

Dan


1 Answers

You have circular imports:

MainFrame.py is indirectly importing MainApp.py, and MainApp.py is importing MainFrame.py. As a result, when MainApp.py is importing MainFrame.py, the RPMWindow class hasn't been defined yet and you get the ImportError.

like image 52
interjay Avatar answered Mar 08 '23 17:03

interjay