Skip to content
Advertisement

Define the variable of a function call indirectly

I have two files file1.py and file2.py.

I execute a function from file2.py which executes a function from file1.py.

# tree/file1.py

def transfer(.., token="Y"):
    ...
# tree/file2.py

from .file1 import transfer

def secure(..):
    ...
    transfer(..) #the `token` argument does not need to be called here.

def main(..):
    ...
    secure(..)

The transfer function from file1.py is used in several other files in the tree.

Could I, from outside the tree, set the token variable for the transfer function in my file1.py? Which would be applied for all these executions.

# outside the tree folder
from tree.file2 import main
token = ?
# choose the token variable and apply it to the transfer function 
main(..)

This would save me from overloading the code and having to put a token argument to all the functions. I want the user to be able to choose his token. Avoid this:

from tree.file2 import main
token = "X"
# choose the token variable and apply it to the transfer function 
main(.., token=token)
# and be forced to put the token argument to all functions..

Advertisement

Answer

My suggestion would be that file1.py should be left alone because if you ever want to use a different token the function is already defined to take a token: def transfer(.., token):

One possibility is to make an intermediary:

# file1a.py
from .file1 import transfer as tr

def transfer(...):
    token = "X"
    tr(..., token)

Now all other modules need to have this: from .file1a import transfer

(if you have hundreds of files and you don’t want to change the import, you could swap the contents of file1.py for file1a.py)

You can also effectively mock out the actual function and make all functions automatically call your own function which supplies the required token:

from tree.file1 import transfer as tr

def transfer(...):
    token = "X"        # this function substitutes a different token
    return tr(..., token)  # call to the real function

import tree.file1 as file1
file1.transfer = transfer   # this sets up the mock from here

from tree.file2 import main

main(...)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement