Home > Enterprise >  Passing imports to a script from inside an external method
Passing imports to a script from inside an external method

Time:05-18

I have kind of a tricky question, so that it is difficult to even describe it. Suppose I have this script, which we will call master:

#in master.py
import slave as slv
def import_func():
    import time
slv.method(import_func)

I want to make sure method in slave.py, which looks like this:

#in slave.py
def method(import_func):
    import_func()
    time.sleep(10)

actually runs like I imported the time package. Currently it does not work, I believe because the import stays exists only in the scope of import_func(). Keep in mind that the rules of the game are:

  1. I cannot import anything in slave.py outside method
  2. I need to pass the imports which method needs through import_func() in master.py

I know it can theoretically be done through importlib, but I would prefer a more straightforward idea, because if we have a lot of imports with different 'as' labels it would become extremely tedious and convoluted with importlib. I know it is kind of a quirky question but I'd really like to know if it is possible. Thanks

CodePudding user response:

Have import_func return time

#in master.py
import slave as slv
def import_func():
    import time
    return time

And have method save the return value so it can be used.

#in slave.py
def method(import_func):
    time = import_func()
    time.sleep(10)

CodePudding user response:

What you can do is this in the master file:

#in master.py
import slave as slv
def import_func():
    import time
    return time
slv.method(import_func)

Now use time return value in the slave file:

#in slave.py
def method(import_func):
    time = import_func()
    time.sleep(10)

Why would you have to do this? It's because of the application's stack. When import_func() is called on slave.py, it imports the library on the stack. However, when the function terminates, all stack data is released from memory. So the library would get released and collected by the garbage collector.

By returning time from import_func(), you guarantee it continues existing in memory once the function terminates executing.

Now, to import more modules? Simple. Return a list with multiples modules inside. Or maybe a Dictionary for simple access. That's one way of doing it.

  • Related