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

Michael Hudson mwh at python.net
Sat Dec 4 20:21:07 CET 2004

Armin Rigo <arigo at tunes.org> writes:

> 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? :-)

Can't do it, at least not simply, as the 'mode' __slot__ is accessed
via a (member?) descriptor in the class's dictionary, which makes it a
challenge to define a property with the same name!  Hmm, you can
probably do some gross metaclass hackery, like so:

class ReadOnlySlots(type):
    def __new__(cls, name, bases, ns):
        nt = type.__new__(cls, name, bases, ns)
        for slotname in nt.__dict__.get('__slots__', []):
            descr = nt.__dict__[slotname]
            def getter(ob, d=descr):
                return descr.__get__(ob, type(ob))
            setattr(nt, slotname, property(getter))
        return nt

class Test(object):
    __metaclass__ = ReadOnlySlots
    __slots__ = ('a',)

But this still leaves the problem of how you actually set these slots
to anything in the first place!  I presume code like

t = Test()

Test.a.fget.func_defaults[-1].__set__(t, 1)

print t.a

is to be discouraged :-)


  > so python will fork if activestate starts polluting it?
  I find it more relevant to speculate on whether Python would fork
  if the merpeople start invading our cities riding on the backs of 
  giant king crabs.                 -- Brian Quinlan, comp.lang.python

More information about the Pypy-dev mailing list