2

I've got the following code (shortened for clarity):

face.py:

from frame import *

class Face(Frame):
    def hello(self):
        print 'hello'

frame.py:

from face import *

class Frame(object):
  def __init__(self, image):
    self.image = image

I'm getting the following error:

Traceback (most recent call last):
  File "2.py", line 2, in <module>
    from frame import *
  File "/home/code/iris/frame.py", line 4, in <module>
    from face import *
  File "/home/code/iris/face.py", line 7, in <module>
    class Face(frame.Frame):
NameError: name 'frame' is not defined

which I think is to do with the way I've either:

  • Set up my 'imports'
  • Set up my classes

Any ideas what I've done wrong? Also, if anyone can explain where 'import' is necessary that would be helpful!

Thanks! Chris.

cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • 3
    Why are you importing face from frame? You've got a circular import. – Jayanth Koushik Apr 18 '14 at 07:51
  • One of my Frame functions will create a new Face - so I figured I'd want it loaded, right? – cjm2671 Apr 18 '14 at 07:52
  • 2
    Seems like you need to redesign your classes. Circular dependencies are not a good idea. – Jayanth Koushik Apr 18 '14 at 07:53
  • Frame is an image, and face is a copied region from the image, with extra methods. Frame.find_faces() should return Face objects, each of which are images themselves. What would be the 'right' structure? – cjm2671 Apr 18 '14 at 07:56

1 Answers1

3

You are entering into the trap of circular dependency. Your face class is depending on the frame class and your frame class is depending on face class thus creating a circular deadlock like situation. Taking reference from Handle circular dependencies in Python modules?

There are ways around this problem in python: The good option: Refactor your code not to use circular imports. The bad option: Move one of your import statements to a different scope.

Community
  • 1
  • 1
Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56
  • Would the solution be to create a super class for Frame & Face, such that Frame & Face were side-by-side, and both could inherit common functions from the superclass? – cjm2671 Apr 18 '14 at 08:01
  • @cjm2671 Yes that's a much better solution – Ankur Aggarwal Apr 18 '14 at 08:03
  • A much simpler fix may be to drop the `from module import *` syntax and just import the module itself (and later use `module.obj` rather than just `obj`). If you only have class and function definitions at the top level, you can usually get away with circular imports. – Blckknght Apr 18 '14 at 08:58