properties and formatting with self.__dict__

Mark McEahern mark at
Wed Feb 19 15:14:52 CET 2003

I hope the following example is not too obtuse, but it shows something that
I thought was surprising about properties.  Attempting to format a string
(traceback follows, with code at the end of the message) with named
parameters and expecting the property to show up naively via self.__dict__
generates this error:

  Traceback (most recent call last):
    File "./", line 23, in ?
      print p
    File "./", line 19, in __repr__
      return template % self.__dict__
  KeyError: full_name

I'm not asking for workarounds because there are many and they are obvious.
I guess I'm wondering whether this is a likely stumbling block in the
intersection of string formatting and the use of properties?


// mark

#!/usr/bin/env python

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def get_full_name(self):
        return '%s %s' % (self.first_name, self.last_name)

    full_name = property(get_full_name)

    def __repr__(self):
        template = '<Person ' \
                   'first=%(first_name)s ' \
                   'last=%(last_name)s ' \
        return template % self.__dict__

p = Person('mark', 'mceahern')

print p


More information about the Python-list mailing list