Accessors in Python (getters and setters)

Bruno Desthuilliers onurb at xiludom.gro
Thu Jul 20 08:40:31 EDT 2006


Gerhard Fiedler wrote:
(snip)
> 
> I'm not sure, but there's one thing that has a potential to be the real
> issue: what's the common way to create a property that is read-write for
> the implementation and "read-only" for the interface? 

class Foo(object):
  @apply
  def _imp():
    def fget(self):
      # code here
    def fset(self, val):
      # code here
    return property(**locals())

  @apply
  def api():
    def fget(self):
      return self._imp
    def fset(self, val):
      raise SomeException('read-only, sorry')
    return property(**locals())


(snip)

> So... _is_active is considered implementation. Don't mess with me, it says.
> But the users of the class need access to it: read access. Do you just say
> "read access isn't changing anything, so just use _is_active"?

Certainly not.

> The
> disadvantage is that the outside code is sprinkled with accesses to
> attributes with leading underscores, which I assume looks kind of scary. Or
> do you rename _is_active to is_active, indicating that access to it is
> indeed allowed?

Certainly not (given I want is_active to be read-only).

> Then you would have to do something in the attribute
> accessors to control the write access -- because that still isn't a good
> idea. But I need want to be able to write to it from inside the class...
> but how, if the attribute accessor is preventing that?

Note that a read-only property named 'is_active' returning the value of
an attribute named '_is_active' doesn't prevent direct access to
'_is_active' attribute, neither from the class nor from the client code.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list