0

I have a function (func.py). Structure of which look like this:

database = 'VENUS'

def first_function():
    print("do some thing")

def second_function():
    print("call third function)
    third_function()  

def third_function(db = database):
    print("do some other thing")

I need to import this function and used the inner defined function. But, I want to use a different key for database. Basically, I want to overwrite database = 'VENUS' and use database = 'MARS' while second function call the third function. is there any way to do this?

Robin
  • 1
  • 2
  • Does this answer your question? [Override globals in function imported from another module](https://stackoverflow.com/questions/49076566/override-globals-in-function-imported-from-another-module). – jfaccioni Mar 03 '20 at 18:24

2 Answers2

0

Just provide the database name as argument

first_function("MARS")
second_function("MARS")
Yogesh Aggarwal
  • 1,071
  • 2
  • 12
  • 30
0

So the problem here, if I understood correctly, is that the default argument for func.third_function is defined at import time. It doesn't matter if you later modify the func.database variable, since the change will not reflect on the default argument of func.third_function.

One (admittedly hacky) solution is to inject a variable using a closure over the imported function. Example:

file.py:

x = 1
def print_x(xvalue = x)
    print(xvalue)

Python console:

>>> import file
>>> file.print_x()
1
>>> file.x = 10
>>> file.print_x()  # does not work (as you're probably aware)
1
>>> def inject_var(func_to_inject, var): 
        def f(*args, **kwargs): 
            return func_to_inject(var, *args, **kwargs) 
        return f
>>> file.print_x = inject_var(file.print_x, 10)
>>> file.print_x()  # works
10

So using the inject_var as written above, you could probably do:

func.third_function = inject_var(func.third_function, "MARS")
jfaccioni
  • 7,099
  • 1
  • 9
  • 25