Search code examples
pythonpython-3.xfunctionpython-decorators

Delay default arguments being read until function is called


I have functions and variables spread over multiple files and am trying to not create a web of imports.

In one file there contains a function. In another variables, as well as the application of those functions (So 2 files total).

The application of the functions requires the functions (obviously) but the function requires the variables.

I wish to be able to do something like the following.

[EDIT: I want to define the variable after the function is defined]

def function(arg1, arg2 = a):
    return arg1 + arg2

a = 5

function(4)

What I would like it to output is 9. However it instead producers an error complaining that a is not defined (it doesn't get further than the function so is unable to read the variable).

I want the function to only try to find the variable once the function has actually been run. I know very little about decorators but I sense that this might be a way of doing this.

If I do something like

def function_1(a):
    def function_2(arg1, arg2 = a):
        return arg1 + arg2

a = 5

Then it doesn't complain however I now need to call upon function_1 to run function_2.

If someone could either point me in the right direction or tell me what I'm doing is not possible that would be very much appreciated.


Solution

  • Use None:

    def function(arg1, arg2=None):
        if arg2 is None:
            arg2 = a
        return arg1 + arg2
    
    a = 5
    
    function(4)
    

    That said, using a global like a to affect the function result might not be the best approach. Globals make code hard to reason about, and hard to test.