Circular imports and class fields in python3

2024/10/14 1:12:18

Okay, I do understand that this topic is old as hell, but I couldn't find an answer to the particular question that I am asking.

Let's say that we have a very simple structure: two files, a.py and b.py, their contents being:

a.py

import bclass C:lal = 4class A:kek = 12lol = b.B()

b.py

import aclass B:aa = a.C()

Trying to run python b.py, we get:

Traceback (most recent call last):File "b.py", line 1, in <module>import aFile ".../a.py", line 1, in <module>import bFile ".../b.py", line 3, in <module>class B:File ".../a.py", line 5, in A                                                                                  aa = a.C()
AttributeError: module 'a' has no attribute 'C'

BUT if we move the import b line AFTER the C class, the script launches and produces no errors.

I have not found any mention of this whatsoever in any answers here on SO. The question here is: Why does this happen and how to escape this?

This is a particularly important question for the Django framework. When I have many models, I try splitting them into many files. It is very easy to get a cyclic import there.

Answer

In python when you import a module then it first import all module that defines at the top of the module, If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module.

so when you try to import b.py module in a.py then it first import all module that listed in b.py is a.py (import a) if module not listed in sys.modules . and still module b.py not completely executed so b.py module is not added into sys.modules

after that, it tries to import a.py and in a.py it tries first import all module that import in a.py is b.py

so it's a basic cycle a.py try to import b.py and b.py try to import a.py

enter image description here

For that problem, Solution is import one module or class inside the class, Not at the top of the module

as per your example

a.py

class C:lal = 4class A:import bkek = 12lol = b.B()

b.py

import aclass B:aa = a.C() 

or

a.py

import b
class C:lal = 4class A:kek = 12lol = b.B()

b.py

class B:import aaa = a.C() 

for detailed information discussion

Python issue

https://en.xdnf.cn/q/118011.html

Related Q&A

Bad HTTP response returned from the server. Code 500

I have a problem to use pywinrm on linux, to get a PowerShell Session. I read several posts and questions on sites about that. But any that can solve my question. The error is in the Kerberos autenti…

Iterate one list of synsets over another

I have two sets of wordnet synsets (contained in two separate list objects, s1 and s2), from which I want to find the maximum path similarity score for each synset in s1 onto s2 with the length of outp…

Flask werkzeug.routing.BuildError

I doing a flask app and when i try to put a link to redirect a user to his profile page by callingBuildError: Could not build url for endpoint profile. Did you forgetto specify values [business_name]?…

getting attribute of an element with its corresponding Id

suppose that i have this xml file :<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5"> <article><article id="11234"><source><hostn…

How to install selenium python on Mac

Ive downloaded the Selenium zip file for python and it contains the folder with the setup.py. It says on python.org that I have to type in terminal python setup.py install but it gives me this error th…

aws s3 - object has no attribute server_side_encryption

Can someone please explain the differences in these two calls. The first one gives the correct server_side_encryption and the second one gives an error. The other attributes give the same value-#!/usr/…

Removing nested for loop to find coincidence values

I am currently using a nested for loop to iterate through to arrays to find values that match a certain criterion. The problem is that this method is incredibly inefficient and time consuming. I was to…

Combine two pandas DataFrame into one new

I have two Pandas DataFrames whose data from different sources, but both DataFrames have the same column names. When combined only one column will keep the name.Like this:speed_df = pd.DataFrame.from_d…

Reasons of slowness in numpy.dot() function and how to mitigate them if custom classes are used?

I am profiling a numpy dot product call. numpy.dot(pseudo,pseudo)pseudo is a numpy array of custom objects. Defined as:pseudo = numpy.array([[PseudoBinary(1), PseudoBinary(0), PseudoBinary(1)],[PseudoB…

How to open cmd and run ipconfig in python

I would like to write a script that do something like that: open the cmd and run the commend "ipconfig" and than copy my ip and paste it to a text file. I wrote the beginning of the script …