Method / Functions - What are the differences?

J

John Posner

John Posner a écrit :
... I was thinking
today about "doing a Bruno", and producing similar pieces on:

* properties created with the @property decorator

* the descriptor protocol

I'll try to produce something over the next couple of days.

Starting to think about a writeup on Python properties, I've
discovered that the official Glossary [1] lacks an entry for
"property" -- it's missing in both Py2 and Py3!

Here's a somewhat long-winded definition -- comments, please:

---------------------------------------------
An attribute, *a*, of an object, *obj*, is said to be implemented as a
property if the standard ways of accessing the attribute:

* evaluation: print obj.a
* assignment: obj.a = 42
* deletion: del obj.a

... cause methods of a user-defined *property object* to be invoked.

Hmmm... a couple remarks:

1/ "property" is actually the name of a Python builtin type. It's also
pretty much used in general OO litterature for what we name
"attributes". So I think it would be better to avoid confusion between
"property" as the builtin type, "property" as synonym for attribute, and
"property" as the more specific concept of "computed attribute" - which
is what you're describing here.

As far as I'm concerned, I prefer to stick to "computed attribute" for
the generic case, and only use "property" when the computed attribute is
actually implemented using the builtin property type.

Yes, I had already decided that the first sentence of the glossary
definition needs to be, "A property is a computed attribute".
2/ depending on how the computed attribute is implemented, the
computation needs not happen on ALL get/set/del access - you can have
non-binding descriptors (that is, not implementing __set__).

Yes, but IMHO that information belongs in the full writeup, not in the
glossary definition. I've added the phrase "some or all" in the glossary
definition (see below).
Also, the "standard" access also include getattr(), setattr() and
delattr() (might be worth a note).


/attribute/user-defined object/ here ?


Yes you can, and it's even actually pretty common:

Of course -- and I realize that I was introducing confusion, rather than
enlightenment, with my example. I think the point is too subtle for a
(necessarily short) glossary definition, so I'm removing the example
from the definition.
# example.py
from somewhere import RGBColor

class Foo(object):
def _get_color(self):
return str(self._color)
def _set_color(self, val):
self._color = RGBColor.from_string(val)
color = property(fget=_get_color, fset=_set_color)

def __init__(self, colorvalue):
self.color = colorvalue

[OFF-TOPIC] Wow, Thunderbird 3.0.2 nuked the indentation in the code
above. :-(
It's actually a type, not a function.

Ah, yes. Thanks.
The "property object" IS an instance of a class that implements the
descriptor protocol. The property type is just a "generic" descriptor:

# naive (and incomplete) python implementation of the property type

class property(object):
def __init__(self, fget, fset=None, fdel=None)
self._fget = fget
self._fset = fset
self._fdel = fdel

def __get__(self, instance, cls):
if instance is None:
return self
return self._fget(instance)

def __set__(self, instance, value):
if not self._fset:
raise AttributeError("can't set attribute")
self._fset(instance, value)

def __del__(self):
if not self._fdel:
raise AttributeError("can't delete attribute")
self._fdel(instance)

Good stuff for the full writeup on properties.

As far as I'm concerned, I'd "plan" such a paper as:

"""
What's a property ? It's a computed attribute implemented using the
builtin "property" type.

Ok, so far it doesn't help much. So
1/ what's a computed attribute, and
2/ what is the property type ?

1/ your above explanation about what's a computed attribute in general,
then a brief explanation of how computed attributes are implemented in
python -> IOW, the descriptor protocol

2/ my above snippet !-)

I agree. I'm not sure whether the "brief explanation of how computed
attributes are implemented in Python" belongs in the *properties*
writeup or the *descriptors* writeup. (I think they should be separate,
to avoid making readers brains explode.) I'll make the (initial) call
when/if I get that far!

"""

I think the way you started explaining computed attributes wrt/
attribute access could be a pretty good way to explain the descriptor
protocol, since the mapping from get/set/del access to __get__, __set__,
and __del__ magic methods is then pretty obvious.

But YMMV of course, so by all mean feel free to discard all or parts of
the above remarks !-)

HTH


Here's my leaner, meaner glossary definition of *property*:

-------------------
A property is a computed attribute: an attribute, a, of an object, obj,
is said to be implemented as a property if some or all of the standard
ways of accessing the attribute:

* evaluation: result = obj.a
* assignment: obj.a = 42
* deletion: del obj.a

.... cause methods of another user-defined object to be invoked. This
other object can be an instance of the built-in type *property*, or as
an instance of a class that implements the descriptor protocol.
 
J

John Posner

[ cross-posting to edu-sig ]

Bruno (and anyone else interested) --

As I promised/threatened, here's the *start* of a write-up on
properties, aimed at non-advanced Python programmers:

http://www.jjposner.net/media/python-properties-0310.pdf

I'm interested in corrections, of course. But I'm also interested in
opinions as to whether this somewhat lengthy treatment is worth the
effort -- does it improve on existing write-ups?

Tx,
John
 
E

Edward Cherlin

[ cross-posting to edu-sig ]

Bruno (and anyone else interested) --

As I promised/threatened, here's the *start* of a write-up on properties,
aimed at non-advanced Python programmers:

 http://www.jjposner.net/media/python-properties-0310.pdf

I'm interested in corrections, of course. But I'm also interested in
opinions as to whether this somewhat lengthy treatment is worth the effort
-- does it improve on existing write-ups?

I find that it will explain things to those who already understand
most of the concepts. However, I felt as though I were being led
through a maze without knowing where we were headed. This suggests
that the concepts can be re-ordered in a manner that will help your
readers more, and then we can refactor further. (Yes, you can apply
Extreme Programming concepts to create Extreme Documentation,
including consultations with users, pair or group writing, frequent
refactoring, and more, as at FLOSSManuals.net.)

Who is your expected audience?
 
G

Gabriel Genellina

As I promised/threatened, here's the *start* of a write-up on
properties, aimed at non-advanced Python programmers:

http://www.jjposner.net/media/python-properties-0310.pdf

I'd use 'function' instead of 'procedure', as this last word is very
uncommon in Python literature (also, "the procedure's return value..." may
look very strange to some people).

I'm unsure if one should make a distinction 'storage attribute' vs.
'method attribute', or even if it makes things actually more clear. I
think you could present the motivating idea first ("I want to execute some
code when accessing an attribute") and only later talk about properties
and descriptors (as written, the reader still doesn't know how to define a
simple property and you've already talked about deleting attributes...)
 
J

John Posner

I'd use 'function' instead of 'procedure', as this last word is very
uncommon in Python literature (also, "the procedure's return value..." may
look very strange to some people).

I was trying to avoid the function-vs-method swamp, and so I used
"procedure". I agree that it was an unfortunate strategy. In a rewrite,
I'm using "function" for the most part
I'm unsure if one should make a distinction 'storage attribute' vs.
'method attribute', or even if it makes things actually more clear.

Agreed -- I was trying too hard to be helpful, and introduced
unnecessary terminology.
... I
think you could present the motivating idea first ("I want to execute some
code when accessing an attribute") and only later talk about properties

That was my intention. I hope it comes across more clearly in the rewrite.
and descriptors (as written, the reader still doesn't know how to define a
simple property and you've already talked about deleting attributes...)

That doesn't bother me. It's OK to describe capabilities -- but not give
how-to's -- in an overview section.


I find that it will explain things to those who already understand
most of the concepts. However, I felt as though I were being led
through a maze without knowing where we were headed.

...
Who is your expected audience?

I was headed toward having the reader *really* understand the @property
decorator. And I was intending that reader to be a non-advanced Python
user -- say, at the CS 101 level. I'm now convinced that such a goal was
"a bridge too far". It has a lot moving parts, including a prerequisite
that is a major topic in itself -- the descriptor protocol. That puts
the goal way beyond reach.




There's another draft at:

http://www.jjposner.net/media/python-properties-0318.pdf


Many thanks for your comments,
John
 
A

Aahz

Bruno (and anyone else interested) --

As I promised/threatened, here's the *start* of a write-up on
properties, aimed at non-advanced Python programmers:

http://www.jjposner.net/media/python-properties-0310.pdf

I'm interested, but not interested enough to download a PDF and fire up
a PDF reader. Are you really using features that require PDF instead of
just writing a web page?
--
Aahz ([email protected]) <*> http://www.pythoncraft.com/

"Many customs in this life persist because they ease friction and promote
productivity as a result of universal agreement, and whether they are
precisely the optimal choices is much less important." --Henry Spencer
 
S

Steve Holden

Aahz said:
I'm interested, but not interested enough to download a PDF and fire up
a PDF reader. Are you really using features that require PDF instead of
just writing a web page?

For us standard browser users it's a single click, of course.

Are you really forced to use an environment that can't start a PDF
reader by clicking on a link?

I appreciate that some people are disabled in ways that rule out reading
a PDF, but since John has gone to some personal trouble to write this
document he's surely entitled to choose his medium ...

regards
Steve
 
J

John Posner

I'm interested, but not interested enough to download a PDF and fire up
a PDF reader. Are you really using features that require PDF instead of
just writing a web page?


No, I compose text using a WYSIWYG editor, and I assumed that PDF was a
convenient format for others.

I've been working on the writeup, and marking it up for use on the
Python Wiki. So I've gone ahead and published it:

http://wiki.python.org/moin/ComputedAttributesUsingPropertyObjects

For good measure, I've also been working on an updated writeup for
"property" in the "Built-in Functions" section of the official Python
docs. A draft is in HTML format at:

http://cl1p.net/jjp_python_property_ref.html/

Thanks for your interest! All comments are most welcome.

-John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top