0

I have folder and code structure like this

root folder
|
|---core folder
|     |
|     |----transaction.py
|     |            
|     |----executetransaction.py       
|
|---test folder
      |
      |----test_execute_transaction.py

transaction.py

class Transaction:
    def __init__(self,json):
        print("in create object")

executetransaction.py

from transaction import Transaction

def execute_transaction(json):
    trsobj = Transaction(json)

test_execute_transaction.py

import sys
sys.path.append("../")

from core import executetransaction
executetransaction.execute_transaction({"a":"b"})

when I execute test_execute_transaction, it is able to import executetransaction from core folder but I get ModuleNotFoundError: No module named 'transaction' on the import code line in executetransaction module.

If I runexecute_transaction({"a":"b"}) in executetransaction module then transaction is imported as expected and I get "in create object".

I have added empty __init__.py in all folders.

This is my first time posting question here, please tell me if more details are required.

Amit
  • 3
  • 2
  • Does `executetransaction` run properly when not testing or do you get the no module named 'transaction' error? – Braden Holt Mar 10 '19 at 20:23
  • @BradenHolt, yes, it runs well without error – Amit Mar 10 '19 at 21:53
  • It sounds like a circular import issue but tough to know without seeing more of your code. Check this: https://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python – Braden Holt Mar 10 '19 at 22:05
  • Thanks, I have added code to the question. From where I look, I don't seem to import in circular manner, there's import tree for sure. – Amit Mar 11 '19 at 02:56

2 Answers2

0

This may help you Using local imports

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory. docs.python.org/3/tutorial/modules

Rambod
  • 2,355
  • 1
  • 14
  • 14
0

Ok your problem is how you import the transaction module in executetransaction.py.

Change from transaction import Transaction to from .transaction import Transaction. The dot operator tells python that you're wanting to import from the current package.

Braden Holt
  • 1,544
  • 1
  • 18
  • 32