opt12
opt12

Reputation: 320

Python: How to obtain the actual parameters of a function call as a dictionary?

In a python class's __init__ function I want to store all parameters that are passed in as a dictionary to restore the object later on. It's not about the function signature like I could get it form the inspect module, but about the actual parameters and values passed in with the recent call.

Currently, I write code like this:

def __init__(self, param1, param2, param3 = 12, **kwargs):
    self.init_dict = {
         'param1': param1,
         'param2': param2,
         'param3': param3,
    }
    self.init_dict.update(**kwargs)
    ...

I think the first lines to store the positional and named parameters to the init_dict are quite tedious.

Isn't there a possibility in python to just get all parameters as a dict and do it like I do with **kwargs?

My gut feeling tells me, that this should be easy, however, I didn't find the correct buzzword for googling.

THX!

Upvotes: 1

Views: 130

Answers (2)

A Kareem
A Kareem

Reputation: 608

If you want the arguments passed to the __init__ function without the pesky self and kwargs variable then you can simply remove them.

And as long as the call to locals is the first line of the __init__ then it will include exactly only the parameters passed to it.

class student():
    def __init__(self, name, *args, **kwargs):
        self.init_dict = locals()
        self.init_dict = {x: self.init_dict[x] for x in self.init_dict if (x is not 'self') and (x is not 'kwargs')}

        random_number = 1234
        self.random_string = 'hello'


    def show_init_params(self):
        print(self.init_dict)

And if we create an instance like so

mike = student('mike', 'A', 'Biology', gpa=3.9)
mike.show_init_params()

The output should be

{'name': 'mike', 'args': ('A', 'Biology')}

Upvotes: 0

jfaccioni
jfaccioni

Reputation: 7509

You can do this with a locals() call:

class A:
    def __init__(self, a, b, *args, **kwargs):
        self.init_dict = locals()

a = A(1, 2, 'aa', foo='bar')
print(a.init_dict)

Output:

{'self': <__main__.A at 0x7f3e5dd7fdf0>, 'a': 1, 'b': 2, 'args': ('aa',), 'kwargs': {'foo': 'bar'}}

Upvotes: 2

Related Questions