possible attribute-oriented class

Ken Newton krnewton at gmail.com
Fri Sep 4 12:55:36 EDT 2009


<top_posting>
I like this version very much. I'm ready to put this into practice to see
how it
works in practice.

A minor point: I envision this to be used in a context where all key values
are
strings (legal attribute identifiers). But constructing an AttrClass from a
dict
or setting values directly with the dict syntax can allow any valid item as
a
dict key -- specifically numbers, tuples, etc. If the user of this class
chooses
to do this, a number of the items become inaccessible to the attribute
syntax.
In my case, I think this won't be a problem since I anticipate that values
will
always be set by the attribute syntax, but it might be an issue for other
uses.
</top_posting>

On Fri, Sep 4, 2009 at 6:01 AM, Jan Kaliszewski <zuo at chopin.edu.pl> wrote:

> [originally from python-list at python.org,
>  crossposted to python-ideas at python.org]
>
[snip]

>  class AttrDict(dict):  # (or maybe from OrderedDict)
>      "It's only a model. (Shhh!)"
>
>      def __getattr__(self, name):
>          if name.startswith('_'):
>              raise AttributeError("AttrDict's key can't "
>                                   "start with underscore")
>          else:
>              return self[name]
>
>      def __setattr__(self, name, value):
>          self[name] = value
>
>      def __delattr__(self, name):
>          del self[name]
>
>      def __repr__(self):
>          return '{0}({1})'.format(self.__class__.__name__,
>                                     dict.__repr__(self))
>      def __str__(self):
>          return self._as_str()
>
>      def _gen_format(self, indwidth, indstate):
>          indst = indstate * ' '
>          ind = (indstate + indwidth) * ' '
>          yield ('\n' + indst + '{' if indstate else '{')
>          for key, val in self.items():
>              valstr = (str(val) if not isinstance(val, AttrDict)
>                        else val._as_str(indwidth, indstate + indwidth))
>              yield '{ind}{key}: {valstr}'.format(ind=ind, key=key,
>                                                  valstr=valstr)
>          yield indst + '}'
>
>      def _as_str(self, indwidth=4, indstate=0):
>          return '\n'.join(self._gen_format(indwidth, indstate))
>
>      def _as_dict(self):
>          return dict.copy(self)
>
>
>  # Test code:
>  if __name__ == '__main__':
>      struct = AttrDict()
>      struct.first = 1
>      struct.second = 2.0
>      struct.third = '3rd'
>      struct.fourth = [4]
>      print(struct)
>      # output:
>      # {
>      #     'second': 2.0
>      #     'fourth': [4]
>      #     'third': '3rd'
>      #     'first': 1
>      # }
>
>      del struct.fourth
>
>      print(repr(struct))
>      # output:
>      # AttrDict({'second': 2.0, 'third': '3rd', 'first': 1})
>
>      print(struct.first)  # (static access)
>      # output:
>      # 1
>
>      for x in ('first', 'second', 'third'):
>          print(struct[x])  # (dynamic access)
>      # output:
>      # 1
>      # 2.0
>      # 3rd
>
>      struct.sub = AttrDict(a=1, b=2, c=89)
>      print(struct._as_dict())
>      # output:
>      # {'second': 2.0, 'sub': AttrDict({'a': 1, 'c': 89, 'b': 2}),\
>      #                                  'third': '3rd', 'first': 1}
>
>      print(struct._as_str(8))
>      # output:
>      # {
>      #         second: 2.0
>      #         sub:
>      #         {
>      #                 a: 1
>      #                 c: 89
>      #                 b: 2
>      #         }
>      #         third: 3rd
>      #         first: 1
>      # }
>
>
> What do you think about it?
>
> Cheers,
> *j
>
> --
> Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090904/4edcb57c/attachment-0001.html>


More information about the Python-list mailing list