0

i have a function with about 20-30 parameters

def function (a,b,c,d,e,....):

     ....

those paramenters may have any value, including "None".
I want to reasign a specifique string to each var that has the value "None" before my function does its magic.

But I dont want to have a huge block of code such as:

if a is None:
     ....
if b is None: ....

How can I go through each var and reasign its value if the condition is met?

ty

epattaro
  • 2,330
  • 1
  • 16
  • 29

3 Answers3

2

Unless you are doing something pretty exotic, this kind of thing is usually better handled by collecting the variables in a data structure, e.g. a dict like so:

def function(**kwargs):
    default = 42
    for key, val in kwargs.items():
        if val is None:
            kwargs[key] = default
    ...
    print(kwargs)

# Example call
function(a=1, b=None)

You can assign to individual variables using the magic of exec, but it's generally not advised. Furthermore, it's not clear to me how one can successfully use this inside of a function as e.g. exec('a = 42') doesn't actually change the value of the local a variable.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
  • ty. thats what i was looking for. fyi: the function takes a bunch of strings as parameters, but what generates the strings can also produce a None element, depending on user interaction (html component). – epattaro Jun 24 '19 at 16:07
  • 2
    This assumes that the function is called with keyword arguments; if I try `function(1,None)`, it will fail. – Scott Hunter Jun 24 '19 at 16:08
1

If you have so many arguments to the function, then you can try using iterable unpacking operator * instead of explicitly defining each argument. In that you you will have more control over the contents of the arguments:-

def function(*args):
    args = list(args)
    for x, y in enumerate(args):
        if y is None:
            args[x] = "default_value"
    print(args)

Then do a function call similar to :-

function(123, 3, None, "hello")

OUTPUT:-

[123, 3, 'default_value', 'hello']
Vasu Deo.S
  • 1,820
  • 1
  • 11
  • 23
0

I'm not recommending doing this, but if you insist:

def function(a,b,c,d,e,...):
    myvars = locals()         # Get a dictionary of parameters
    arg_names = myvars.keys() # Get their names
    for k in arg_names:       # Replace the ones whose value is None
        if myvars[k] == None:
            myvars[k] = 'None'
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • that works even better. ty. i should problaby be using a dictionary as an input, or is there a better solution? – epattaro Jun 24 '19 at 16:12