Reputation: 755
Given an object already created, what is the best way to figure out how it was created? Basically, I would like to figure out the actual parameters during the object creation (eventually the actual parameters passed to the class init method).
Note that I mean the actual parameters here, not the formal parameters. The formal parameters may perhaps accept 20 different parameters, maybe 16 of them are optional with default values each. In the actual call (i.e. creating the object instance), perhaps only 5 parameters are given, and 3 of them happens to be the same as default value.
What I would like to do is to retrieve these 5 parameters and their values, after the object has been created.
For code example, lets say the class of interest is called Kmodel. Kmodel constructor accepts 20 different parameters (16 of them don't need to be specified by caller).
In caller's code, this would be something like:
kmodel = Kmodel( param1 = 10, param2 = None, param3 = "name3", param4 = [1, 3, 5], param5 = dict("keyx": "valuey"})
...
Later call a method to find out the actual parameters calling Kmodel( )
figure_out_actual_params(kmodel)
Now the implementation of the code to figure out:
def figure_out_acutal_params( kmodel ):
...
here is the code that needs to be implemented to reconstruct the actual parameters calling Kmodel creation
Thanks!
PS. Note that there are several similar questions on this topic and I have read them all. I don;t think this question is the same. For my question, I can query all the internal object attributes of an object, and I still won't be able to tell which one has been specified during the actual object construction. (The sticky issue is the actual parameter may happen to be the default value.)
Upvotes: 5
Views: 508
Reputation: 5774
You can add a section to the __init__
section that saves the input variables perhaps?
class MyThing:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
self.initial_settings = [arg1, arg2]
Then as long as you never overwrite self.initial_settings
it will hold the values it was initialized with (leaving you free to change self.arg1
for instance). You can also include some if
logic to determine if a default parameter was overwritten upon creation (although I don't believe there is a way to tell if an initial value was supplied that equated to the default value). Otherwise I think you will have to use dir(some_object_instance)
to determine current attributes, but I don't think there is any other way to determine initial attributes besides storing them during initialization...
Upvotes: 1