Home > Blockchain >  Fill all requiered args with "None" if they are empty
Fill all requiered args with "None" if they are empty

Time:09-06

The args I must assign are v0, v1 ... v18

sx.set_attribute(v5="test",**{f"v{i}": None for i in range(19) if not eval(f"v{i}") == ""}})

I'm getting the following error message:

NameError: name 'v0' is not defined

CodePudding user response:

This wrapper function will remove additional keyword arguments:

import inspect


def set_kwargs_default_none(fn):
    fn_kwargs = [p.name for p in inspect.signature(fn).parameters.values() if p.kind >= inspect.Parameter.POSITIONAL_OR_KEYWORD]

    def wrapped(*args, **kwargs):
        tmp = {k: None for k in fn_kwargs}
        tmp.update(kwargs)
        return fn(*args, **tmp)

    return wrapped


@set_kwargs_default_none
def foo(v0, v1, v2, v3, *, v4=1):
    return (v0, v1, v2, v3)


test_args = {f"v{i}": i for i in range(3)}

foo(**test_args)

Result:

(0, 1, 2, None, None)

And without the wrapper:

TypeError: foo() missing 2 required positional arguments: 'v3' and 'v4'
  • Related