How much introspection is implementation dependent?
James Stroud
jstroud at mbi.ucla.edu
Sat Feb 3 02:59:05 EST 2007
George Sakkis wrote:
> On Feb 2, 6:56 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
>
>> Hello,
>>
>> I wanted to automagically generate an instance of a class from a
>> dictionary--which might be generated from yaml or json. I came up with this:
>>
>> (snip)
>>
>> ==
>>
>> #! /usr/bin/env python
>>
>> # automagical constructor
>> def construct(cls, adict):
>> dflts = cls.__init__.im_func.func_defaults
>> vnames = cls.__init__.im_func.func_code.co_varnames
>>
>> argnames = vnames[1:-len(dflts)]
>> argvals = [adict.pop(n) for n in argnames]
>>
>> return cls(*argvals, **adict)
>>
>> def test():
>>
>> class C(object):
>> def __init__(self, arg1, arg2, kwa3=3):
>> self.argsum = arg1 + arg2
>> self.kwsum = kwa3
>> def __str__(self):
>> return "%s & %s" % (self.argsum, self.kwsum)
>>
>> # now a dict for autmagical generation
>> adict = {'arg1':1, 'arg2':2, 'kwa3':42}
>>
>> print '======== test 1 ========'
>> print adict
>> print construct(C, adict)
>>
>> adict = {'arg1':1, 'arg2':2}
>> print
>> print '======== test 2 ========'
>> print adict
>> print construct(C, adict)
>>
>> if __name__ == "__main__":
>> test()
>
> What's the point of this ? You can call C simply by C(**adict). Am I
> missing something ?
>
> George
>
Maybe there is something wrong with my python.
py> class C:
... def __init__(a, b, c=4):
... print a,b,c
...
py> C(**{'a':10, 'b':5, 'c':4})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got multiple values for keyword argument 'a'
James
More information about the Python-list
mailing list