Skip to content

Circular import when inventree.purchase_order is imported first #314

Open

Description

@carmelom

Problem

If inventree.purchase_order is the first inventree module that a program imports, Python raises an ImportError.

main.py

from inventree.purchase_order import PurchaseOrder

output:

$ python .\main.py
Traceback (most recent call last):
  File "inventree-python-test\main.py", line 1, in <module>
    from inventree.purchase_order import PurchaseOrder
  File "inventree-python-test\.venv\Lib\site-packages\inventree\purchase_order.py", line 6, in <module>
    import inventree.company
  File "inventree-python-test\.venv\Lib\site-packages\inventree\company.py", line 6, in <module>
    import inventree.order
  File "inventree-python-test\.venv\Lib\site-packages\inventree\order.py", line 7, in <module>
    from inventree.purchase_order import (
    ...<3 lines>...
    )
ImportError: cannot import name 'PurchaseOrder' from partially initialized module 'inventree.purchase_order' (most likely due to a circularimport) (inventree-python-test\.venv\Lib\site-packages\inventree\purchase_order.py)

Versions: inventree 0.25.0, Python 3.14.10. The import cycle is also on master.

Cause

The import chain is purchase_order.py → company.py → order.py → purchase_order.py.

order.py uses from inventree.purchase_order import (...). For this statement, the module must be fully initialized. At this point, purchase_order is only partially initialized.

Workaround

Import inventree.order before inventree.purchase_order.

import inventree.order
from inventree.purchase_order import PurchaseOrder

runs successfully.

Suggested fix

In company.py, import the order modules directly, not the inventree.order proxy:

 import inventree.base
-import inventree.order
+import inventree.purchase_order
+import inventree.return_order
+import inventree.sales_order

Then change the 6 references in the Company methods:

  • inventree.order.PurchaseOrder → inventree.purchase_order.PurchaseOrder
  • inventree.order.SalesOrder → inventree.sales_order.SalesOrder
  • inventree.order.ReturnOrder → inventree.return_order.ReturnOrder

Reason: company.py uses these classes only inside methods. A plain import statement is safe in an import cycle.

I tested this change locally. Each of these modules imports correctly as the first import: purchase_order, sales_order, return_order, company, order and api.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions