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.

P A N
  • 5,642
  • 15
  • 52
  • 103

1 Answers1

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)
Community
  • 1
  • 1
Yaroslav Admin
  • 13,880
  • 6
  • 63
  • 83
  • 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:` – P A N Aug 23 '15 at 13:15
  • 2
    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`). – Yaroslav Admin Aug 23 '15 at 13:18
  • From [documentation](https://docs.python.org/2/library/stdtypes.html#dict): `key in d` Return True if `d` has a key `key`, else False. Sorry if my wording was a bit misleading. – Yaroslav Admin Aug 23 '15 at 13:25