Do all dynamic languages ​​have a problem with circular import?

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 starting from the shell:

python first.py

I get an error: ImportError: cannot import name Second

Do other similar dynamic languages ​​like Ruby have such a problem? The reason I ask is because I am facing this problem in a Django project, where 2 models are dependent on each other. I know that possible solutions are redesigning a project or importing it on demand. I just want to know if developers of other dynamic languages ​​have encountered this problem.

+3
source share
6 answers

Python . , , , , . , import first, first.First from first import First.

, - . .

+12

, . . , , .

. , .

Python , , . , , , , .

+3

, , , .

, Python/Django, , -

#appA/models.py
class A(models.Model):
  b = models.ForeignKey('appB.b')

#appB/models.py
class B(models.Model):
  a = models.ForeignKey('appA.a')

( ); Django , , . , .

+2

. . . , , , . - !

+1

: , , . :

first.py

# first.py
class First:
  def __init__(self):
    print 'Second'
from second import Second

second.py

# second.py
class Second:
    def __init__(self):
        print 'Second'
from first import First

The link to import Fredrik Lundh is worth a read. However, as others have advised you, you'd better opt out of the code to completely eliminate circular imports.

+1
source

This is not a problem with "dynamic" languages. This is an architectural matter. You need to take a better look at how you structured things.

0
source

Source: https://habr.com/ru/post/1733274/


All Articles