[pypy-dev] question about read only attributes of my file object

Armin Rigo arigo at tunes.org
Sat Dec 4 17:48:23 CET 2004

Hi Laura,

On Sat, Dec 04, 2004 at 03:48:14PM +0100, Laura Creighton wrote:
> Ok, this property takes effect even in __init__, rats.

Indeed.  But __init__ can still write to the read-only attribute by bypassing 
the property and writing to self.__dict__ directly.

For reading: the name you use, getval(), is misleading.  It should be called
getmode(), because it is specific to the 'mode' attribute.  Indeed, it only
receives one argument:

class C(object):
    def __init__(self):
        self.__dict__['mode'] = 'rU'
    def getmode(self):
        return self.__dict__['mode']
    mode = property(getmode)

Another note.  It's possible to limit the set of attributes that the 'file'
instances can take (to enforce the failure of user code like 'f.silly = 42').  
This is done with __slots__, but using it requires some rewriting because then
the instances don't have a __dict__ any more.  In this case it's better to use
underscored names:

class file(object):
    __slots__ = ['_mode']

    def __init__(self):
        self._mode = 'rU'

    def _getmode(self):
        return self._mode
    mode = property(_getmode)

The drawback here is that 'self._mode' is a public and writeable attribute,
but we probably don't care because of the leading underscore.  If we do care,
it's probably possible to have a slot called exactly 'mode' which is hidden by
the 'mode' property, but I can't figure out what kind of obcure hacks are
needed to do that...  mwh? :-)

A bientot,


More information about the Pypy-dev mailing list