Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
attrdict.py
#6
i added an __init__() method which handles zero or more arguments of dict/attrdict or list/tuple of zero or more key:value 2-sequence pairs.

class attrdict(dict):
    '''Class that is like a dictionary with items usable like attributes.

#---------------------------------------------------------------
# purpose       class that is a dictionary with items usable
#               like attributes
#
# init usage    object = attrdict(dictionary)
#               object = attrdict(dictionary,key=value...)
#               object = attrdict(key=value...)
#
# attr usage    object.name
#
# dict usage    object[key]
#
# note          attribute usage is like string keys that are
#               limited to what can be a valid identifier.
#
# thanks        [email protected]
#---------------------------------------------------------------
'''
    def __init__(self,*args,**opts):
        arn = 0
        for arg in args:
            arn += 1
            if isinstance(arg,(attrdict,dict)):
                self.update(arg)
            elif arg and isinstance(arg,(list,tuple)):
                an = -1
                for ar in arg:
                    an += 1
                    if isinstance(ar,(list,tuple)) and len(ar)==2:
                        self[ar[0]] = ar[1]
                    else:
                        raise TypeError('not a 2-sequence at ['+str(an)+'] of argument '+str(arn))
            else:
                raise TypeError('argument '+str(arn)+' is not a sequence')
        if opts:
            if isinstance(opts,(attrdict,dict)):
                self.update(opts)
            else:
                raise TypeError('options ('+repr(opts)+') is not a dictionary')
    def __getattr__(self, key):
        return self[key]
    def __setattr__(self, key, value):
        self[key] = value
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
attrdict.py - by Skaperen - Jan-02-2019, 08:30 PM
RE: attrdict.py - by scidam - Jan-05-2019, 01:45 AM
RE: attrdict.py - by Skaperen - Jan-09-2019, 06:40 PM
RE: attrdict.py - by nilamo - Jan-09-2019, 06:53 PM
RE: attrdict.py - by Skaperen - Jan-10-2019, 12:51 AM
RE: attrdict.py - by Skaperen - Jan-10-2019, 06:35 AM
RE: attrdict.py - by Gribouillis - Jan-10-2019, 08:49 AM
RE: attrdict.py - by Skaperen - Jan-11-2019, 03:47 PM
RE: attrdict.py - by nilamo - Jan-11-2019, 04:26 PM
RE: attrdict.py - by Skaperen - Jan-12-2019, 12:57 AM
RE: attrdict.py - by nilamo - Jan-13-2019, 02:10 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020