Search code examples
pythonfunctionargumentsoutputvarying

How can you output a varying argument in Python?


I am writing a function in Python.

So lets say I have 3 arguments in this function:

Function (arg1, arg2, arg3)
  arg1 = arg2 * arg3

When the function is called, it is as such:

function(arg1=var1, arg2=var2, arg3=var3)

Now the thing is, these variables, (var1, var2, var3) vary in the case of this function being called. So they could be var4, var5, var6, etc.

Given that these variables vary, what would be the syntax to make this function change a varying argument?

ie. arg1 = arg2 * arg3 changes arg1. Because arg1 = var1.

What I need is somehow for arg1 to stand in as an actual proxy to var1 so that not only is arg1 changed but var1 is changed also.

This is evidently not doable with simply with arg1=var1

I assume this could also be done with other function commands or structure. How does not really concern me I just need to output a change into a varying argument.

Edit This function is specifically designed to take an argument called, not necessarily knowing what it is, and then inside of the function, that argument which is converted into a formula variable such as x in y = mx + b, needs to be converted back into its variable target, all inside of the function.

The problem here is that I don't know how to target the original variable.

So if it were function(a=cats, b=dogs, c=mice)

a = c/2 - b*2

how do I then set cat=a when cat is variable?

I can't just say cat=a because maybe the input is function(a=bird, b=flys, c=cats)


Solution

  • def f(x, y):
        return x*y
    
    a, b = 1, 2
    
    c = f(a, b)
    

    Instead of having your function try to alter its arguments directly, return any results the function produces. This turns out to be a much cleaner, more useful way to structure your code. For example, you can do

    print f(1, f(2, 3))
    

    instead of having to create temporary variables:

    f(a, 2, 3)
    f(b, 1, a)
    print b
    

    Instead of doing

    f(arg1=var1, arg2=var2, arg3=var3)
    f(arg1=var4, arg2=var5, arg3=var6)
    

    do the following:

    var1 = f(var2, var3)
    var4 = f(var5, var6)