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.

JavaScript
JavaScript

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.

JavaScript

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:

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement