Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Method / Functions - What are the differences?

4 views
Skip to first unread message

Michael Rudolf

unread,
Feb 28, 2010, 7:38:14 AM2/28/10
to
Out of curiosity I tried this and it actually worked as expected:

>>> class T(object):
x=[]
foo=x.append
def f(self):
return self.x


>>> t=T()
>>> t.f()
[]
>>> T.foo(1)
>>> t.f()
[1]
>>>

At first I thought "hehe, always fun to play around with python. Might
be useful sometimes" - but then It really confused me what I did. I
mean: f is what we call a method, right? But was is foo? It is not a
method and not a classmethod as it accepts no self and no cls.
So that leaves staticmethod? OK, fair, as x is "static" here anyway this
reflects what it does. But then consider this:

>>> class T(object):
def __init__(self):
self.x=[]
self.foo=self.x.append
def f(self):
return self.x


>>> y=T()
>>> y.x
[]
>>> y.foo(1)
>>> y.x
[1]
>>> a=T()
>>> a.x
[]
>>> a.foo(2)
>>> a.x
[2]
>>>

Note that all I did was moving the list and foo into the instance. Still
no self and no cls, but also no static behaviour any more.

So is foo just nothing of the above and really only a class/instance
attribute which happens to be callable?

Perhaps this all does not matter, but now I am really confused about the
terminology. So: what makes a method a method? And of what type?

Regards,
Michael

Alf P. Steinbach

unread,
Feb 28, 2010, 9:08:49 AM2/28/10
to
* Michael Rudolf:

> Out of curiosity I tried this and it actually worked as expected:
>
> >>> class T(object):
> x=[]
> foo=x.append
> def f(self):
> return self.x
>
>
> >>> t=T()
> >>> t.f()
> []
> >>> T.foo(1)
> >>> t.f()
> [1]
> >>>
>
> At first I thought "hehe, always fun to play around with python. Might
> be useful sometimes" - but then It really confused me what I did. I
> mean: f is what we call a method, right? But was is foo?

foo is (refers to) an object that supports call notation and that forwards calls
somewhere else, in this case to append on a list.

You might call it (descriptive) a call forwarder, or (C# or general terminology)
a delegate, or (Python 2.x) a bound method.


<example>
>>> "Hello".upper
<built-in method upper of str object at 0x00BA16E0>
>>> f = "Hello".upper
>>> f
<built-in method upper of str object at 0x00BA16E0>
>>> f()
'HELLO'
>>>
>>>
>>>
>>> f.__self__
'Hello'
>>> f.__call__
<method-wrapper '__call__' of builtin_function_or_method object at 0x00BDD170>
>>> print( f.__doc__ )
S.upper() -> str

Return a copy of S converted to uppercase.
>>> _
</example>


A common use for delegates is as command handlers in a GUI application, and in
general for event notifications.


Cheers & hth.,

- Alf

Rob Williscroft

unread,
Feb 28, 2010, 9:24:06 AM2/28/10
to
Michael Rudolf wrote in news:hmdo3m$287$1...@news.urz.uni-heidelberg.de in
comp.lang.python:

> Note that all I did was moving the list and foo into the instance. Still
> no self and no cls, but also no static behaviour any more.

Yes in the first case foo was an attribute of the class, and in the second
an attribute of aon instance of the class.

In both cases it was a bound method, something similar too:

lambda item : T.x.append( item )

Michael Rudolf

unread,
Feb 28, 2010, 11:39:03 AM2/28/10
to
Am 28.02.2010 15:08, schrieb Alf P. Steinbach:
> >>> "Hello".upper
> <built-in method upper of str object at 0x00BA16E0>
> >>> f = "Hello".upper
> >>> f
> <built-in method upper of str object at 0x00BA16E0>
> >>> f()
> 'HELLO'
> >>>
> >>>
> >>>
> >>> f.__self__
> 'Hello'

Holy hand grenade.
You have no Idea how enlightened I feel right now :D

Thank you, "bound method" was the term I forgot and your example...
...totally revealed the internals behind this to me. Especially the last
line I quoted.
I mean, I always knew *that* this works, but I never knew *why*.

Regards,
Michael

Bruno Desthuilliers

unread,
Mar 1, 2010, 2:59:55 PM3/1/10
to
Michael Rudolf a ᅵcrit :

> Out of curiosity I tried this and it actually worked as expected:
>
>>>> class T(object):
> x=[]
> foo=x.append
> def f(self):
> return self.x
>
>
>>>> t=T()
>>>> t.f()
> []
>>>> T.foo(1)
>>>> t.f()
> [1]
>>>>
>
> At first I thought "hehe, always fun to play around with python. Might
> be useful sometimes" - but then It really confused me what I did. I
> mean: f is what we call a method, right?

Wrong. It's a function. T.f is an unbound method (in python 2.x at
least) and t.f is a bound method.

> But was is foo?

A bound method. Bound to x, of course.

> It is not a
> method and not a classmethod as it accepts no self and no cls.

Yes it does. Else how would t.foo(4) (or T.foo(4)) append 4 to x ?

> Perhaps this all does not matter,

It does.

> but now I am really confused about the
> terminology. So: what makes a method a method?

The right question is: what makes a function a method !-)

> And of what type?

Answer here:

http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/bd71264b6022765c/3a77541bf9d6617d#doc_89d608d0854dada0

I really have to put this in the wiki :-/

John Posner

unread,
Mar 1, 2010, 8:07:37 PM3/1/10
to pytho...@python.org
On 3/1/2010 2:59 PM, Bruno Desthuilliers wrote:


Bruno, I performed a light copy-edit of your writeup and put in some
reStructuredText (reST) markup. The result is at:

http://cl1p.net/bruno_0301.rst/

The only sentence that I think needs work is:

Having access to itself (of course), the
instance (if there's one) and the class, it's easy for it
to wrap all this into a **method** object.

Maybe this?

With the instance object (if any) and class object available,
it's easy to create a method object that wraps the function object.


Begging pardon for my presumptuousness,
John

Bruno Desthuilliers

unread,
Mar 2, 2010, 3:57:52 AM3/2/10
to
John Posner a ᅵcrit :

> On 3/1/2010 2:59 PM, Bruno Desthuilliers wrote:
>
>> Answer here:
>>
>> http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/bd71264b6022765c/3a77541bf9d6617d#doc_89d608d0854dada0
>>
>>
>> I really have to put this in the wiki :-/
>
>
> Bruno, I performed a light copy-edit of your writeup and put in some
> reStructuredText (reST) markup. The result is at:
>
> http://cl1p.net/bruno_0301.rst/

Cool.

>
> The only sentence that I think needs work is:
>
> Having access to itself (of course), the
> instance (if there's one) and the class, it's easy for it
> to wrap all this into a **method** object.
>
> Maybe this?
>
> With the instance object (if any) and class object available,
> it's easy to create a method object that wraps the function object.

That's perfect.

But there's also a typo to fix in the Python implementation of the
Method object: in the call method, it should inject self.im_self as
first arg, not self.im_func. This had been spotted by someone named John
Posner, IIRC !-)


>
> Begging pardon for my presumptuousness,

Begging pardon for my laziness :-/

John Posner

unread,
Mar 2, 2010, 9:17:00 AM3/2/10
to pytho...@python.org
On 3/2/2010 3:57 AM, Bruno Desthuilliers wrote:
>>
>> With the instance object (if any) and class object available,
>> it's easy to create a method object that wraps the function object.
>
> That's perfect.


Fixed.

> But there's also a typo to fix in the Python implementation of the
> Method object: in the call method, it should inject self.im_self as
> first arg, not self.im_func. This had been spotted by someone named John
> Posner, IIRC !-)


Fixed (oops!).

I've updated the text at this location:

> http://cl1p.net/bruno_0301.rst/

I think the ball is back in your court, Bruno. I'd be happy to help more
-- feel free to contact me off-list, at jjpo...@optimum.net.

Best,
John

Eike Welk

unread,
Mar 2, 2010, 5:00:29 PM3/2/10
to
John Posner wrote:
> I've updated the text at this location:
>
> > http://cl1p.net/bruno_0301.rst/

I think this is a very useful writeup!

It would be perfect with a little bit of introduction that says:
1. - What it is: "The rough details of method look-up";
2. - which contains some of the questions that that made that authors write
the text. This way people with similar questions can find it with Google.

Additionally the link to the relevant section in the Python documentation
would be great. I can't find it!

A link to an article about the details of class creation and metaclasses
would be good too.


Thanks for writing this great little text,
Eike.

Bruno Desthuilliers

unread,
Mar 3, 2010, 5:56:03 AM3/3/10
to
Eike Welk a �crit :

> John Posner wrote:
>> I've updated the text at this location:
>>
>> > http://cl1p.net/bruno_0301.rst/
>
> I think this is a very useful writeup!
>
> It would be perfect with a little bit of introduction that says:
> 1. - What it is: "The rough details of method look-up";
> 2. - which contains some of the questions that that made that authors write
> the text. This way people with similar questions can find it with Google.
>

John, do you think you could something with the following ?

"""
"Is it a function ? is it a method ? No, it's... " - or : What's in a
Python method ?

Python newcomers often have hard time understanding the "magic" behind
Python's methods - and truth is that Python's object model can be a bit
peculiar when compared to most mainstream (or not-so-mainstream) OOPLs.
As a matter of fact, there are quite a few threads on c.l.py with either
direct or indirect questions about what makes a Python method, and I
must have explained the whole mechanism at least 3 or 4 times there. The
following text is an edited version of my last attempt, as edited,
corrected and published by John Posner, MayHisNameBePraised(tm).

This text isn't meant as a replacement for neither the official
FineManual(tm)[XXX : relevant link] nor the very excellent - if somehow
technical - 'Descriptors how-to' [XXX : relevant link]. It's mostly a
brief but hopefully helpful overview of what exactly is a Python method,
and how Python magically inserts the 'self' or 'cls' argument to method
calls.
"""

Feel free to edit / amend / rewrite / trash at will - you're now
officially in charge of publishing this text !-)

John Posner

unread,
Mar 3, 2010, 9:58:46 AM3/3/10
to pytho...@python.org
On 3/3/2010 5:56 AM, Bruno Desthuilliers wrote:
> Eike Welk a �crit :
>> John Posner wrote:
>>> I've updated the text at this location:
>>>
>>> > http://cl1p.net/bruno_0301.rst/
>>
>> I think this is a very useful writeup!
>> It would be perfect with a little bit of introduction that says:
>> 1. - What it is: "The rough details of method look-up";
>> 2. - which contains some of the questions that that made that authors
>> write the text. This way people with similar questions can find it
>> with Google.
>>
>
> John, do you think you could something with the following ?

Sure thing, Bruno. I'll incorporate/edit your new text below into a
Python Wiki entry. The headings in the Documentation table of contents
page (http://wiki.python.org/moin/Documentation) seem pretty sober, so I
plan to use a straightforward title:

FromFunctionsToMethods

... instead of the clearly superior ...

ItsAFunctionItsAMethodItsAUseOfTheDescriptorProtocol

Does this article belong in the "Advanced Topics" section of the page?
I'm not sure, but I'll place it there for now. (Alternative suggestions
welcome!)

>
> """
> "Is it a function ? is it a method ? No, it's... " - or : What's in a
> Python method ?
>
> Python newcomers often have hard time understanding the "magic" behind
> Python's methods - and truth is that Python's object model can be a bit
> peculiar when compared to most mainstream (or not-so-mainstream) OOPLs.
> As a matter of fact, there are quite a few threads on c.l.py with either
> direct or indirect questions about what makes a Python method, and I
> must have explained the whole mechanism at least 3 or 4 times there. The
> following text is an edited version of my last attempt, as edited,
> corrected and published by John Posner, MayHisNameBePraised(tm).
>
> This text isn't meant as a replacement for neither the official
> FineManual(tm)[XXX : relevant link] nor the very excellent - if somehow
> technical - 'Descriptors how-to' [XXX : relevant link]. It's mostly a
> brief but hopefully helpful overview of what exactly is a Python method,
> and how Python magically inserts the 'self' or 'cls' argument to method
> calls.
> """
>
> Feel free to edit / amend / rewrite / trash at will - you're now
> officially in charge of publishing this text !-)
>

Yow, the mantle of responsibility weighs heavily upon my poor shoulders!

Film at 11,
John

Bruno Desthuilliers

unread,
Mar 3, 2010, 10:48:43 AM3/3/10
to
John Posner a �crit :

> On 3/3/2010 5:56 AM, Bruno Desthuilliers wrote:
>> Eike Welk a �crit :
>>> John Posner wrote:
>>>> I've updated the text at this location:
>>>>
>>>> > http://cl1p.net/bruno_0301.rst/
>>>
>>> I think this is a very useful writeup!
>>> It would be perfect with a little bit of introduction that says:
>>> 1. - What it is: "The rough details of method look-up";
>>> 2. - which contains some of the questions that that made that authors
>>> write the text. This way people with similar questions can find it
>>> with Google.
>>>
>>
>> John, do you think you could something with the following ?
>
> Sure thing, Bruno. I'll incorporate/edit your new text below into a
> Python Wiki entry. The headings in the Documentation table of contents
> page (http://wiki.python.org/moin/Documentation) seem pretty sober, so I
> plan to use a straightforward title:
>
> FromFunctionsToMethods

What about "TheMagicBehindMethods" ? Mmm, not sure, so do what you think
is best.

> ... instead of the clearly superior ...
>
> ItsAFunctionItsAMethodItsAUseOfTheDescriptorProtocol
>
> Does this article belong in the "Advanced Topics" section of the page?
> I'm not sure, but I'll place it there for now. (Alternative suggestions
> welcome!)

I spotted this:

http://www.python.org/doc/faq/programming/#what-is-a-method
http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls

Our text is probably a bit too long for a direct inclusion in the FAQ,
so I'd say it should go in the AdvancedTopics, and be linked from the FAQ.

>
> Yow, the mantle of responsibility weighs heavily upon my poor shoulders!

!-)


Thanks for doing the grunt work.

John Posner

unread,
Mar 3, 2010, 11:32:55 AM3/3/10
to pytho...@python.org
On 3/3/2010 9:58 AM, John Posner wrote:

> Film at 11,
> John
>

Done -- see http://wiki.python.org/moin/FromFunctionToMethod

-John

John Posner

unread,
Mar 3, 2010, 12:02:10 PM3/3/10
to pytho...@python.org
On 3/3/2010 10:48 AM, Bruno Desthuilliers wrote:

>
> I spotted this:
>
> http://www.python.org/doc/faq/programming/#what-is-a-method
> http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls
>
>
> Our text is probably a bit too long for a direct inclusion in the FAQ,
> so I'd say it should go in the AdvancedTopics, and be linked from the FAQ.

Linking from the FAQ means changing the official Python documentation,
which requires lots of hoop-jumping-through. I suggest that we content
ourselves with using the Wiki -- at least for now.

>
> Thanks for doing the grunt work.

Pas de quoi.

-John

Bruno Desthuilliers

unread,
Mar 3, 2010, 12:03:37 PM3/3/10
to
John Posner a �crit :

Done and well done !-)
Thanks again for the good job John.

PS : Do you think it could be possible to add link to this page from the
relevant FAQ items ?

http://www.python.org/doc/faq/programming/#what-is-a-method
http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls


Eike Welk

unread,
Mar 3, 2010, 6:33:29 PM3/3/10
to
Bruno Desthuilliers wrote:
> John Posner a écrit :

>> Done -- see http://wiki.python.org/moin/FromFunctionToMethod
>
> Done and well done !-)
> Thanks again for the good job John.

I like it too, thanks to both of you!

I have two small ideas for improvement:
- Swap the first two paragraphs. First say what it is, and then give the
motivation.
- The section about the descriptor protocol is a bit difficult to
understand. But judging from the official descriptor documentation, it seems
to be hard to explain: The official documentation is nearly incomprehensible
(IMHO).

John Posner

unread,
Mar 3, 2010, 6:56:07 PM3/3/10
to eike...@gmx.net
On 3/3/2010 6:33 PM, Eike Welk wrote:
>
> I have two small ideas for improvement:
> - Swap the first two paragraphs. First say what it is, and then give the
> motivation.

No problem -- since this is a Wiki, you can perform the swap yourself!
(If you haven't done it in a day or so, I'll do the deed.)

> - The section about the descriptor protocol is a bit difficult to
> understand. But judging from the official descriptor documentation, it seems
> to be hard to explain: The official documentation is nearly incomprehensible
> (IMHO).

I empathize -- it took me a while to grok descriptors. 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.

-John

Bruno Desthuilliers

unread,
Mar 4, 2010, 5:59:00 AM3/4/10
to
Eike Welk a écrit :

> Bruno Desthuilliers wrote:
>> John Posner a écrit :
>>> Done -- see http://wiki.python.org/moin/FromFunctionToMethod
>> Done and well done !-)
>> Thanks again for the good job John.
>
> I like it too, thanks to both of you!
>
> I have two small ideas for improvement:
> - Swap the first two paragraphs. First say what it is, and then give the
> motivation.

Mmm... As far as I'm concerned, I like it the way its. John ?

> - The section about the descriptor protocol is a bit difficult to
> understand.

I may eventually try to rework it a bit when I'll have time (death march
here currently, duh...)

> But judging from the official descriptor documentation, it seems
> to be hard to explain

Not that easy, indeed. I once posted on c.l.py a longer explanation of
the whole lookup rule stuff, that IIRC included a "naive python
implementation" example. Might be worth trying to google for it and
turning it into another "overview" article.

>: The official documentation is nearly incomprehensible
> (IMHO).

I should probably have a look at it !-)

John Posner

unread,
Mar 4, 2010, 8:35:05 AM3/4/10
to eike...@gmx.net
On 3/4/2010 5:59 AM, Bruno Desthuilliers wrote:
>>
>> I have two small ideas for improvement: - Swap the first two
>> paragraphs. First say what it is, and then give the motivation.
>
> Mmm... As far as I'm concerned, I like it the way its. John ?

I think it doesn't make very much difference. But in the end, I believe
it's the student, not the teacher, who gets to decide what's comprehensible.

What *does* make a difference, IMHO, is getting more people to
participate in the process of shining lights into Python's darker
corners. That's why I encouraged (and still encourage) Eike to roll up
the sleeves and wade into these waters.

Metaphor-mixingly yours,
John

John Posner

unread,
Mar 4, 2010, 4:17:20 PM3/4/10
to
On 3/3/2010 6:56 PM, John Posner wrote:
>
> ... 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. The
attribute is created as a class attribute, not an instance attribute.
Example:

class Widget:
# create "color" as class attribute, not within __init__()
color = <<property-object>>

def __init__(self, ...):
# do not define "self.color" instance attribute

The property object can be created with the built-in function
property(), which in some cases can be coded as a decorator: @property.
The property object can also be an instance of a class that implements
the descriptor protocol.
---------------------------------------------

Tx,
John

[1] http://docs.python.org/glossary.html

Bruno Desthuilliers

unread,
Mar 5, 2010, 7:15:59 AM3/5/10
to
John Posner a écrit :

> On 3/3/2010 6:56 PM, John Posner wrote:
>>
>> ... 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.

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__).

Also, the "standard" access also include getattr(), setattr() and
delattr() (might be worth a note).

> The
> attribute

/attribute/user-defined object/ here ?

> is created as a class attribute, not an instance attribute.
> Example:
>
> class Widget:
> # create "color" as class attribute, not within __init__()
> color = <<property-object>>
>
> def __init__(self, ...):
> # do not define "self.color" instance attribute

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

# 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


> The property object can be created with the built-in function
> property(),

It's actually a type, not a function.

> which in some cases can be coded as a decorator: @property.
> The property object can also be an instance of a class that implements
> the descriptor protocol.

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)


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 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

John Posner

unread,
Mar 5, 2010, 10:10:51 AM3/5/10
to

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).
>
>> The attribute
>
> /attribute/user-defined object/ here ?
>
>> is created as a class attribute, not an instance attribute. Example:
>>
>> class Widget:
>> # create "color" as class attribute, not within __init__()
>> color = <<property-object>>
>>
>> def __init__(self, ...):
>> # do not define "self.color" instance attribute
>
> 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. :-(

>
>
>> The property object can be created with the built-in function property(),
>
> It's actually a type, not a function.

Ah, yes. Thanks.

>
>> which in some cases can be coded as a decorator: @property. The
>> property object can also be an instance of a class that implements the
>> descriptor protocol.
>
> 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.

-------------------

Many thanks, Bruno -- again!

-John

John Posner

unread,
Mar 10, 2010, 9:45:38 AM3/10/10
to pytho...@python.org, edu...@python.org
[ 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

Edward Cherlin

unread,
Mar 10, 2010, 10:31:35 AM3/10/10
to John Posner, edu...@python.org, pytho...@python.org

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?

> Tx,
> John
>
> _______________________________________________
> Edu-sig mailing list
> Edu...@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>

--
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/

Gabriel Genellina

unread,
Mar 10, 2010, 8:37:18 PM3/10/10
to pytho...@python.org, edu...@python.org
En Wed, 10 Mar 2010 11:45:38 -0300, John Posner <jjpo...@optimum.net>
escribió:

> 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...)

--
Gabriel Genellina

John Posner

unread,
Mar 18, 2010, 12:48:35 PM3/18/10
to Gabriel Genellina, Edward Cherlin
On 3/10/2010 8:37 PM, Gabriel Genellina wrote:
> En Wed, 10 Mar 2010 11:45:38 -0300, John Posner <jjpo...@optimum.net>
> escribió:
>
>> 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 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.

And Edward Cherlin wrote:

> 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

Aahz

unread,
Mar 21, 2010, 5:34:28 PM3/21/10
to
In article <mailman.555.12682323...@python.org>,

John Posner <jjpo...@optimum.net> wrote:
>
>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 (aa...@pythoncraft.com) <*> 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

Steve Holden

unread,
Mar 21, 2010, 6:44:11 PM3/21/10
to pytho...@python.org
Aahz wrote:
> In article <mailman.555.12682323...@python.org>,
> John Posner <jjpo...@optimum.net> wrote:
>> 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?

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
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

John Bokma

unread,
Mar 21, 2010, 7:10:01 PM3/21/10
to
aa...@pythoncraft.com (Aahz) writes:

> In article <mailman.555.12682323...@python.org>,
> John Posner <jjpo...@optimum.net> wrote:
>>
>>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?

http://docs.google.com/viewer?url=http%3A%2F%2Fwww.jjposner.net%2Fmedia%2Fpython-properties-0310.pdf

Hth,

--
John Bokma j3b

Hacking & Hiking in Mexico - http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development

John Posner

unread,
Mar 21, 2010, 7:28:43 PM3/21/10
to aa...@pythoncraft.com
On 3/21/2010 5:34 PM, Aahz wrote:
> In article<mailman.555.12682323...@python.org>,
> John Posner<jjpo...@optimum.net> wrote:
>>
>> 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?


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


0 new messages