1

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.

1
  • 1
    You get passed in the values, not the original variables. So no. Commented Aug 23, 2015 at 12:47

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this. But this is looking for parts of strings, is it not? The variables I use are set to False from the start, and are then supposed to switch to True if they are inputted into the function. Although perhaps a workaround is to set the variables to contain their name as a string? As so: x = 'x'; ... if 'x' in variables:
No, it's not. Read linked question about **kwargs carefully. When you call switch(x=5, y=4), your variables will become a dict with two items, like {'x': 5, 'y': 4}. And in operator checks if the item with particular name is present in this dict (effectively checking whether any value was passed in using x=ANY_VALUE).
From documentation: key in d Return True if d has a key key, else False. Sorry if my wording was a bit misleading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.