On Feb 2, 6:56 pm, James Stroud <[EMAIL PROTECTED]> 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

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to