Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ImportError: cannot import name '..' from partially initialized module '..' (most likely due to a circular import)

Tags:

python

I've read the other threads on this but they haven't really helped me.

I have to 2 .py files, both located under ets.routes, called agreements.py and approvals.py. enter image description here

The file agreements.py imports several methods from approvals:

from ets.routes.approvals import getPendingApprovals, getIsApprover

It itself also exposes a utility method which should be available to approvals called authorize_agreement.

Now in approvals.py if I do

from ets.routes.agreements import authorize_agreement

I get the error

ImportError: cannot import name 'getPendingApprovals' from partially initialized module 'ets.routes.approvals' (most likely due to a circular import) 
(C:\gitForVS\app\api\ets\routes\approvals.py)

I can't move authorize_agreement to some external file like utils.py, it really should be in agreements.py because it uses a lot of DB and associated Agreement-level code which is available there. It's just that this function should be imported by its sibling, while it itself imports some of the sibling's functions. Why is that such an issue? Are you required to have 1-way imports (e.g. from approvals -> agreements only) in Python?

like image 630
gene b. Avatar asked Dec 01 '25 06:12

gene b.


1 Answers

The reason you're getting an error is because agreements.py can't import functions from approvals.py while approvals.py is simultaneously trying to import functions from agreements.py (hence the circular import error). One of your modules needs to define the functions the other wants before importing the functions it wants from the other.

For example:

File A:

from fileb import sum2

def sum(a, b):
    return a + b

File B:

def sum2(a, b):
    return a + b + a

from filea import sum # This works
like image 104
Caleb Keller Avatar answered Dec 12 '25 14:12

Caleb Keller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!