0

I have a function with lot of variables passed into it and I need to create an object of it. How can I simplify this code?

obj_in = dict()

if foo:
    obj_in['foo'] = foo
if bar:
    obj_in['bar'] = bar
if john:
    obj_in['john'] = john

UPD: My current idea is:

fields = ['foo', 'bar', 'john']
obj_in = dict()

for field in fields:
    val = locals()[field]
    if val:
        enrich_dict(field, val, obj_in)


def enrich_dict(field: str, val, obj_in: dict):
    obj_in[field] = val

But not really sure of using locals.

D. Make
  • 579
  • 2
  • 6
  • 23

2 Answers2

2

If you need all the parameters and their values from inside the scope of a function, you should use locals(). It will capture the variables in the current scope. If you want the values before you modify them in the function, then call locals at the beginning of the function, otherwise call it at the end.

def func(x, y, z):
    d = locals()
    x = 1
    y = 2
    z = 3
    return d, (x, y, z)

func(11, 12, 13)

>>> ({'x': 11, 'y': 12, 'z': 13}, (1, 2, 3))
Nathan Furnal
  • 2,236
  • 3
  • 12
  • 25
-1

If you don't mind verbose calls, you can change

def f(foo, bar, john)

to

def f(**kwargs)

and then directly use that kwargs dict in the function

Expurple
  • 877
  • 6
  • 13
  • This is the problem. I have to describe each field: https://github.com/tiangolo/fastapi/issues/657 – D. Make Dec 20 '21 at 14:52
  • Not only does this make the code unmaintainable, you also change the meaning of the code, imagine `foo` is `0` and that is an invalid input, your code now allows that. – Sayse Dec 20 '21 at 14:54
  • @Sayse not necessarily, just `if kwargs['foo'] == 0: return` or did I miss something? – Matiiss Dec 20 '21 at 14:56
  • @D.Make Could you explain this in a bit more detail? What should I look at in that issue? And what exactly do you mean by "describe each field"? My answer only concerns the function arguments, not fields – Expurple Dec 20 '21 at 14:56
  • @Matiiss - What would be the point in changing it if you're just going to do that? – Sayse Dec 20 '21 at 14:56
  • @Sayse in case of variable number of arguments, but I guess that default values could be used then instead, right now I really see just one use case and that would be with classes and inheritance so yes, there is no point to do that here, also OP hasn't made it clear enough about the circumstances – Matiiss Dec 20 '21 at 14:59