x.abc vs x['abc']

Discussion in 'Python' started by Gunter Henriksen, May 13, 2009.

  1. Presuming it is very common to have objects created
    on the fly using some sort of external data
    definitions, is there an obvious common standard
    way to take a dict object and create an object
    whose attribute names are the keys from the dict?

    I realize I can do something like:

    >>> d = {"hello": "world"}
    >>> x = type("", (object,), d)()
    >>> x.hello

    world

    but that seems like an arcane way to do something
    which would ideally be transparent... if there is
    a function in the standard library, that would be
    good, even if I have to import it. I guess there is
    collections.namedtuple... that would not look much
    prettier... but the main thing to me is for it to
    be the same way everybody else does it. I do not
    prefer the new object be a dict, but it would be ok.
     
    Gunter Henriksen, May 13, 2009
    #1
    1. Advertising

  2. Gunter Henriksen

    alex23 Guest

    On May 14, 5:49 am, Gunter Henriksen <>
    wrote:
    > Presuming it is very common to have objects created
    > on the fly using some sort of external data
    > definitions, is there an obvious common standard
    > way to take a dict object and create an object
    > whose attribute names are the keys from the dict?


    I've always liked this approach, which I first saw in a post by Alex
    Martelli:

    >>> class Bunch(object):

    .... def __init__(self, **kwargs):
    .... self.__dict__.update(kwargs)
    ....
    >>> b = Bunch(a=1,b=2,c=3)
    >>> b.a

    1
    >>> b.b

    2
    >>> b.d = 22
    >>> b.d

    22


    Elegant.
     
    alex23, May 15, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jiong Feng
    Replies:
    0
    Views:
    836
    Jiong Feng
    Nov 19, 2003
  2. Colin Peters

    Special character to &abc equivalents

    Colin Peters, May 7, 2005, in forum: ASP .Net
    Replies:
    8
    Views:
    2,302
    =?Utf-8?B?UGF1bCBQYXJraW5zb24=?=
    May 9, 2005
  3. Bruce Sam
    Replies:
    15
    Views:
    7,931
    John C. Bollinger
    Nov 19, 2004
  4. vsgdp

    ABC inheriting from ABC

    vsgdp, Sep 24, 2005, in forum: C++
    Replies:
    1
    Views:
    311
    vsgdp
    Sep 24, 2005
  5. Replies:
    4
    Views:
    154
Loading...

Share This Page