P A N
P A N

Reputation: 5922

Python: Detect if certain variable is inputted into function argument

How can I make a function recognize if a certain variable is inputted as an argument?

I would like to input a number of variables into the function, and if they are present, return corresponding binary variables as True to the program.

#variables to test: x, y, z

def switch(*variables):
    for var in list(variables):
        #detect if var is the variable x:
            switch_x = True
        #detect if var is the variable y:
            switch_y = True
        #detect if var is the variable z:
            switch_z = True

switch(x, y, z)

if switch_x is True:
    #Do something

Note that I'm looking to test if the variables themselves are inputted into the function. Not the values that the variables contain.

Upvotes: 1

Views: 83

Answers (1)

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

No, that's not possible to do with *args, but you can use **kwargs to achieve similar behaviour. You define your function as:

def switch(**variables):
    if 'x' in variables:
        switch_x = True
    if 'y' in variables:
        switch_y = True
    if 'z' in variables:
        switch_z = True

And call like:

switch(x=5, y=4)
switch(x=5)
# or
switch(z=5)

Upvotes: 2

Related Questions