Simple cross import in python

I want to separate code in different class and put them to different files. However those class are dependent on each other.

main.py:

from lib import A, B

def main():
    a = A()
    b = B()
    a.hello()
    b.hello()

if __name__ == '__main__':
    main()

lib/_init_.py:

from a import A
from b import B

lib/a.py:

import lib.B

class A():
    def __init__(self):
        print "A"

    def hello(self):
        print "hello A"
        b = B()

lib/b.py:

import lib.A

class B():
    def __init__(self):
        print "B"

    def hello(self):
        print "hello B"
        a = A()

Is it possible to do that in Python?

EDIT:

I get this error message:

pydev debugger: starting
Traceback (most recent call last):
  File "eclipse-python/plugins/org.python.pydev_2.7.1.2012100913/pysrc/pydevd.py", line 1397, in <module>
    debugger.run(setup['file'], None, None)
  File "eclipse-python/plugins/org.python.pydev_2.7.1.2012100913/pysrc/pydevd.py", line 1090, in run
    pydev_imports.execfile(file, globals, locals) #execute the script
  File "main.py", line 2, in <module>
    from lib import A, B
  File "lib/__init__.py", line 1, in <module>
    from a import A
  File "lib/a.py", line 1, in <module>
    import lib.B
ImportError: No module named B

Answer

Instead of importing the modules on top, you could import the other module within the hello function.

class B():
    def __init__(self):
        print "B"

    def hello(self):
        from lib import A
        print "hello B"
        a = A()

Leave a Reply

Your email address will not be published. Required fields are marked *