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

Armin Rigo arigo at tunes.org
Sat Dec 4 18:15:24 CET 2004

Hi Laura,

On Sat, Dec 04, 2004 at 06:07:33PM +0100, Laura Creighton wrote:
> So -- do you really want me to use the properties?  I now think they are
> icky.

Ick!  Yes!  People who use __getattr__() or __setattr__() should be shot
without even waiting for dawn.  Basically, they don't cooperate well with the
whole new-style class mecanisms.

The issue of __slots__ vs no-__slots__ is related to: do we want to restrict
the attributes that file instances can have, or not?  So far I'd say that
restricting them is a good idea, just because CPython does it too.  Whether
CPython's restriction is to be regarded as an implementation wart or a real
planned feature is left open to python-dev's judgement, I guess.

This said, using attribute names like '_mode' on our file class might be a bad
idea because it could potentially conflict with someone's code, where 'file'
is subclassed and a '_mode' attribute is used for another purpose.

To minimize code duplication, note that a common "cookbook" recipe might help
(a replacement for 'property' which always reads/writes the data to the
__dict__ under the member's name):

class member(object):
    def __init__(self, name, readonly=False):
        self.__name__ = name
        self.__readonly__ = readonly
    def __get__(self, obj, cls=None):
        if obj is not None:
            return obj.__dict__[self.__name__]
            return self    # XXX incomplete
    def __set__(self, obj, value):
        if self.__readonly__:
            raise AttributeError, 'attribute %s is read-only' % (
        obj.__dict__[self.__name__] = value
    def __del__(self, obj):
        if self.__readonly__:
            raise AttributeError, 'attribute %s is read-only' % (
            del obj.__dict__[self.__name__]
        except KeyError:
            raise AttributeError, self.__name__    

class file(object):
    def __init__(self):
        self.__dict__['mode'] = 'r+'
    mode = member('mode', readonly=True)

My class member is still incomplete; it would be nice to have a full-featured
class member somewhere in PyPy.  (It's missing unbound access, e.g.  

A bientot,


More information about the Pypy-dev mailing list