Packing function arguments into a dictionary is the opposite ** kwargs

I'm trying to do the opposite of what ** kwargs are doing, and I'm not sure if this is possible. But knowing Python, this is possible :-) I want all the attributes to be clearly designed in my method (for automatic completion and ease of use), and I want to capture them all, say, in the dictionary and beyond.

class Foo(object):
   def __init__(self, a=1, b=2):
      inputs = grab_function_inputs_somehow()
      self.bar(**inputs)

   def bar(self, *args, **kwargs):
      pass

the normal thing is to assign each input to an object parameter, but I don't want to do this for all classes. I was hoping he could pass it on to a method that could be inherited.

+4
source share
2 answers

dict , locals(). :

class Foo(object):
    def __init__(self, a=1, b=2):    
        inputs = locals()
        del inputs['self'] # remove self variable
        print(inputs)


f = Foo() 

:

{'b': 2, 'a': 1}
+7

, :

class Foo(object):
    def __init__(self, **inputs):
        # Have to set your defaults in here
        inputs['a'] = inputs.get('a', 1)
        inputs['b'] = inputs.get('b', 2)
        # Now the rest of your code, as you expected
        self.bar(**inputs)

    def bar(self, *args, **kwargs):
        print("bar got: %s" % kwargs)


# No arguments, use defaults
Foo()           # bar got: {'a': 1, 'b': 2}
# Arguments provided
Foo(a=3, b=4)   # bar got: {'a': 3, 'b': 4}

, , , , , , <dict>.get().

__init__ :

def __init__(self, **inputs):
    # Have to set your defaults in here
    if 'a' not in inputs: inputs['a'] = 1
    if 'b' not in inputs: inputs['b'] = 2
    # Now the rest of your code, as you expected
    self.bar(**inputs)

# or

def __init__(self, **inputs):
    # Have to set your defaults in here
    args = {'a': 1, 'b':2}
    args.update(inputs)
    # Now the rest of your code, as you expected
    self.bar(**args)

.

-1

All Articles