0

I want to call im1.py's want_to_call() method from im2.py Test's class func1() and func1() will be called by im1's some_func() method.... Your help will be appreciated.

im1.py

from im2 import Test

def some_func(value):
    Test.func1()
    print(value)


def want_to_call():
    return 'called from im2'

some_func("ola")

im2.py

from im1 import want_to_call

class Test:
    def func1():
        variable = want_to_call()
        print(variable)
        print('How do I call want_to_call method in im1')


class Test1:
    def func():
        print('Thanks in advance')

Nikhil Bhardwaj
  • 562
  • 10
  • 18
  • 1
    Possible duplicate of [How to avoid circular imports in Python?](https://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python) – ruddra Mar 26 '19 at 13:55
  • @ruddra thanx sir, can u please do it with my question, I'll be thankful for that..... – Nikhil Bhardwaj Mar 26 '19 at 16:16

1 Answers1

3

Don't do that.

The advice to "only import the module" works (How to avoid circular imports in Python?). But you'd be better off putting your functions into more files that are arranged in a hierarchy. In other words, break the cycle. It will be beneficial for the organization of your code, and of your unit tests, and for how you think about your high level problem.

Here, the definitions of want_to_call() and func1() belong in additional files, which both im1 & im2 import.

Tests should depend upon target code, not the other way around.

J_H
  • 17,926
  • 4
  • 24
  • 44
  • your answer is good but I am doing this in django like one is views.py and 2nd file is some services.py, so I want to do that thing only in views.py. And Second thing, importing a file instead of function may create performance problem because I have so many functions and so many things in views.py, by the way your answer is also very helpful thanks – Nikhil Bhardwaj Mar 26 '19 at 15:59
  • Even for views & services, you still have an opportunity to evict common functions into some utility.py file. As far as elapsed time goes, the `import` happens just once when django starts up. Your code is small, relative to the other libraries you are importing, so absent timing results I wouldn't worry much about such overheads, they're not the dominant source of delay. – J_H Mar 26 '19 at 16:46
  • but I tried that code which is given in answer, it is not working or I'm doing this wrong can u please check it once according to their answer – Nikhil Bhardwaj Mar 26 '19 at 16:52