[Python-3000] hash as attribute/property

Guido van Rossum guido at python.org
Tue Apr 4 22:04:30 CEST 2006


On 4/4/06, Barry Warsaw <barry at python.org> wrote:
> Just a data point.  In our API, we've been converting all of our no-arg
> methods to attributes/properties, each of which may or may not be
> writable of course.  It's simplified our Python code enormously, and
> made it much more readable.  Certainly "foo.get_something()" and
> "foo.set_something(thing)" are much better spelled "foo.something" and
> "foo.something = thing".

Right. It sounds like your original API was using Java-style getters
and setters too much, and then converting to Python-style attributes
and properties is an obvious improvement.

> As a general principle, we've been making this conversion for any
> getters and setters that take no arguments, both for pure-Python types
> and C-implemented types.  While we were at it, we changed everything
> that returns a newly formed concrete sequence to returning an iterator
> (which broke code that was doing random access into the sequence, but
> that's another story).

Let me ask a clarification here. Do you now have properties that
return new iterators? That seems a bad idea, for the following reason:
I'd expect these two code sequences to have the same effect:

   a = obj.foo
   b = obj.foo

and

  a = b = obj.foo

If obj.foo were to be a property returning a new iterator on each
access, the first example would end up with a and b separate
(independent) iterators, while the second example would make a and b
aliases for the same iterator. I hope I misunderstood you; something
that returns an iterator should definitely not be a property but a
real method.

> I don't know whether Python 3000 wants to encourage that style, but it
> works well for us.

I certainly want to continue discouraging setter and getter methods
where plain attributes would do.

The question is where to draw the line. I don't believe you really
meant "all no-args methods". Perhaps you meant "all side-effect free
argument-less methods that return the same value each time (or at
least until some explicit change to the object is made) and that can
be computed reasonably cheap"?

The __hash__() method qualifies, which is why it's a tough call (I'll
come back on that; I want to come up with a reason why __hash__()
should remain a method). The iterator-getting example above doesn't
qualify.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list