Is there a way to call the function defined in main.py from the module I import on main.py?

Asked 2 years ago, Updated 2 years ago, 43 views

Thank you for your cooperation.

I'd like to do the following, but I'd like to call fun() defined in main.py from sub.py, where main.py imports it. Is there a way to do it?

#main.py
from sub.py import*
def fun():
    print('test')
I want to show call_fun()#'test'
#sub.py
def call_fun():
    fun()# I want to call the fun() of main.py who is importing myself here. Is it a good way to write?

I think I can give the fun to call_fun(), for example, call_fun(fun), but I don't want to do that.

Also, I want to import sub.py as a file name, so for example, I want to make main2.py work.How should I write sub.py call_fun()?

Thank you for your cooperation.

python python3

2022-09-30 17:50

1 Answers

Is there a way to access parent modules in Python
It seems that we can do it by applying the answers below in the above article.
However, it may not be applicable if you say import in many stages.

For posterity, Iran into this also and camera up with the one liner:

import sys
parent_module=sys.modules ['.'.'.join(_name__.split('.')[:-1]) or '__main_']

The or '__main__' part is just in case you load the file directly it will return it.

The source code will look like this:

  • main.py changes the sub.py line to import:(Cut .py)
from sub import*
  • sub.py uses the above article to retrieve information about the parent module and calls the function.
#sub.py
import sys
parent_module=sys.modules ['.'.'.join(_name__.split('.')[:-1]) or '__main_']

def call_fun():
    parent_module.fun()#Call the fun() of the parent module importing itself here.


2022-09-30 17:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.