Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple cross import in python

Tags:

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 
like image 441
ts_pati Avatar asked Jun 21 '13 00:06

ts_pati


2 Answers

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() 
like image 167
Michael_Scharf Avatar answered Sep 19 '22 19:09

Michael_Scharf


When you have two classes depending on each other usually means that either they really belong to the same module or that you have a too tight coupling that should be resolved using dependency injection.

Now there are indeed a couple corner cases where importing from within the function is the "least worst" solution but that's still something you should avoid as much as possible.

like image 35
bruno desthuilliers Avatar answered Sep 20 '22 19:09

bruno desthuilliers