Adding attributes stored in a list to a class dynamically.

Alex Martelli aleax at
Sun Sep 2 20:46:51 CEST 2007

Nathan Harmston <ratchetgrid at> wrote:

> Hi,
> Sorry if the subject line of post is wrong, but I think that is what
> this is called. I want to create objects with
> class Coconuts(object):
>     def __init__(self, a, b, *args, **kwargs):
>       self.a = a
>       self.b = b
> def spam( l )
>    return Coconuts( l.a, l.b, l.attributes )
> l in a parse line of a file which is a tuple wrapped with
> attrcol......with attributes a, b and attributes (which is a list of
> strings in the format key=value ie...
>        [ "id=bar", "test=1234", "doh=qwerty" ]  ).
> I want to add attributes to Coconuts so that I can do
> print, c.test, c.doh
> HOwever I m not sure how to do this:
> how can i assign args, kwargs within the constructor of coconuts and
> how can I deconstruct the list to form the correct syntax to be able
> to be used for args, kwargs.

If you want to pass the attributes list it's simpler to do that
directly, avoiding *a and **k constructs.  E.g.:

  def __init__(self, a, b, attrs):
    self.a = a
    self.b = b
    for attr in attrs:
      name, value = attr.split('=')
      setattr(self, name, value)

You may want to add some better error-handling (this code just raises
exceptions if any item in attrs has !=1 occurrences of the '=' sign,
etc, etc), but I hope this gives you the general idea.

Note that you'll have trouble accessing attributes that just happen to
be named like a Python keyword, e.g. if you have "yield=23" as one of
your attributes you will NOT be able to just say c.yield to get at that
attribute.  Also, I'm assuming it's OK for all of these attributes'
values to be strings, etc, etc.


More information about the Python-list mailing list