Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all dynamic languages have the circular import issue?

For the following Python code:

first.py

# first.py
from second import Second

class First:
    def __init__(self):
        print 'Second'

second.py

# second.py
from first import First

class Second:
    def __init__(self):
        print 'Second'

After creating the files and running the following from the shell:

python first.py

I get the error: ImportError: cannot import name Second

Do other dynamic languages like Ruby have this kind of issue? The reason I'm asking is because I'm encountering this issue in a Django project where 2 models depend on each other. I know that the possible solutions are re-designing the project or import on demand. I just want to know if devs in other dynamic languages have experienced this issue.

like image 251
Thierry Lam Avatar asked Dec 01 '22 06:12

Thierry Lam


1 Answers

Python can handle circular imports to some extent. In cases where no sense can be made, the solution would probably still not make sense in another language. Most of the problems can be cleared up by using import first and later referring to first.First instead of from first import First.

It would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.

like image 181
Mike Graham Avatar answered Dec 05 '22 05:12

Mike Graham