473,396 Members | 2,039 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Immutability


The way that I read it, Python allows only values (and hence types)
to be immutable, and not class members. The nearest approach to the
latter is to use the name hiding conventions.

Is that correct?
Regards,
Nick Maclaren.
Jun 28 '06 #1
37 1812
Nick Maclaren wrote:
The way that I read it, Python allows only values (and hence types)
to be immutable, and not class members. The nearest approach to the
latter is to use the name hiding conventions.

Is that correct?


You can also make properties that don't allow writing.

class Foo(object):

def __init__(self, bar):
self._bar = bar

@property
def bar(self):
return self._bar

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jun 28 '06 #2

In article <ma***************************************@python. org>,
Robert Kern <ro*********@gmail.com> writes:
|> Nick Maclaren wrote:
|> > The way that I read it, Python allows only values (and hence types)
|> > to be immutable, and not class members. The nearest approach to the
|> > latter is to use the name hiding conventions.
|> >
|> > Is that correct?
|>
|> You can also make properties that don't allow writing.
|>
|> class Foo(object):
|>
|> def __init__(self, bar):
|> self._bar = bar
|>
|> @property
|> def bar(self):
|> return self._bar

Thanks very much. And, what's more, I have even found its documentation!
Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.

One of Python's less-lovable attributes is the inscrutability of its
documentation :-(

But you knew that ....
Regards,
Nick Maclaren.
Jun 28 '06 #3
Nick Maclaren wrote:
In article <ma***************************************@python. org>,
Robert Kern <ro*********@gmail.com> writes:
|> Nick Maclaren wrote:
|> > The way that I read it, Python allows only values (and hence types)
|> > to be immutable, and not class members. The nearest approach to the
|> > latter is to use the name hiding conventions.
|> >
|> > Is that correct?
|>
|> You can also make properties that don't allow writing.
|>
|> class Foo(object):
|>
|> def __init__(self, bar):
|> self._bar = bar
|>
|> @property
|> def bar(self):
|> return self._bar

Thanks very much. And, what's more, I have even found its documentation!
Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.


Is it?

http://docs.python.org/lib/built-in-funcs.html

documents "property" quite well.

Georg
Jun 28 '06 #4

In article <e7**********@news.albasani.net>,
Georg Brandl <g.*************@gmx.net> writes:
|> >
|> > Thanks very much. And, what's more, I have even found its documentation!
|> > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.
|>
|> Is it?
|>
|> http://docs.python.org/lib/built-in-funcs.html
|>
|> documents "property" quite well.

Sigh. No. It's terrible. What it documents is the use of the property
FUNCTION. It does not document what properties ARE, and how they interact
with the rest of the language. Until you know that, it is so ambiguous
as to be almost totally useless - and it is THAT information that needs to
be in the reference manual, but is only in whatsnew2.2.
Regards,
Nick Maclaren.
Jun 28 '06 #5
> Sigh. No. It's terrible. What it documents is the use of the property
FUNCTION. It does not document what properties ARE, and how they interact
with the rest of the language. Until you know that, it is so ambiguous
as to be almost totally useless - and it is THAT information that needs to
be in the reference manual, but is only in whatsnew2.2.


I have to second that - I found myself reading through "What's new" from
various versions to find that specific feature. It would be at least good
to see all of them grouped together to make an easier read. Still, that is
not optimal.

Diez
Jun 28 '06 #6
Nick Maclaren wrote:
The way that I read it, Python allows only values (and hence types)
to be immutable,
I don't understand this sentence. Some types are immutable, some are
not. This has nothing to do with "values" (FWIW, everything in Python is
an object, there's no 'primitive type' vs 'object type' distinction)
and not class members.
If an attribute is of an immutable type, it will still be immutable.

If what you want is 'read-only' attributes, then use properties:

class MyClass(object):
def __init__(self, name):
self._name = name
name = property(fget=lambda self : self._name)
m = MyClass('parrot')
m.name 'parrot' m.name = "toto" Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute

The nearest approach to the
latter is to use the name hiding conventions.


naming conventions are used to denote what's API and what's
implementation. But this won't make an attribute read-only. If you want
an attribute to be part of the API *but* read-only, use the solution above.

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 28 '06 #7
Nick Maclaren <nm**@cus.cam.ac.uk> wrote:
Georg Brandl <g.*************@gmx.net> writes:
|> [ attributions lost ]
|> > Thanks very much. And, what's more, I have even found its documentation!
|> > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.
|> Is it?
|> http://docs.python.org/lib/built-in-funcs.html
|> documents "property" quite well.
Sigh. No. It's terrible. What it documents is the use of the property
FUNCTION. It does not document what properties ARE, and how they interact
with the rest of the language. Until you know that, it is so ambiguous
as to be almost totally useless - and it is THAT information that needs to
be in the reference manual, but is only in whatsnew2.2.


Actually, there's an almost throw-away mention in
http://docs.python.org/ref/descriptor-invocation.html
which gives you what you need (although not, I have to say, in an
easily digestible form).

What I've not seen documented anywhere is the:
@property
def fset(self, value):
...
idiom. It's not obvious from the documentation of the property
function that it can be used as a decorator like this. (cf.
classmethod and staticmethod.)

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Jun 28 '06 #8
Georg Brandl wrote:
Nick Maclaren wrote:
In article <ma***************************************@python. org>,
Robert Kern <ro*********@gmail.com> writes:
|> Nick Maclaren wrote:
|> > The way that I read it, Python allows only values (and hence types)
|> > to be immutable, and not class members. The nearest approach to the
|> > latter is to use the name hiding conventions.
|> >
|> > Is that correct?
|>
|> You can also make properties that don't allow writing.
|>
|> class Foo(object):
|>
|> def __init__(self, bar):
|> self._bar = bar
|>
|> @property
|> def bar(self):
|> return self._bar

Thanks very much. And, what's more, I have even found its documentation!
Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.

Is it?

http://docs.python.org/lib/built-in-funcs.html

documents "property" quite well.

I can't really agree that "quite good" documentation doesn't refer to
the use of property as a decorator. It's obvious that a ncessary upgrade
to the docs didn't happen (and we can all understand why, I am sure).

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Love me, love my blog http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jun 28 '06 #9

Nick Maclaren wrote:
In article <e7**********@news.albasani.net>,
Georg Brandl <g.*************@gmx.net> writes:
|> >
|> > Thanks very much. And, what's more, I have even found its documentation!
|> > Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.
|>
|> Is it?
|>
|> http://docs.python.org/lib/built-in-funcs.html
|>
|> documents "property" quite well.

Sigh. No. It's terrible. What it documents is the use of the property
FUNCTION. It does not document what properties ARE, and how they interact
with the rest of the language. Until you know that, it is so ambiguous
as to be almost totally useless - and it is THAT information that needs to
be in the reference manual, but is only in whatsnew2.2.


There are (unofficial) documentation wikis here:

pytut.infogami.com
pyref.infogami.com
pyfaq.infogami.com

You might like to consider adding the information you perceive to be
lacking.

All the best.

Gerard

Jun 28 '06 #10
Sion Arrowsmith wrote:
What I've not seen documented anywhere is the:
@property
def fset(self, value):
...
idiom. It's not obvious from the documentation of the property
function that it can be used as a decorator like this.


probably because it cannot be used in that way: the "property" function
takes the *getter* as its first argument, so you can only use this for read-
only properties...

</F>

Jun 28 '06 #11
Steve Holden wrote:
Thanks very much. And, what's more, I have even found its documentation!
Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.

Is it?

http://docs.python.org/lib/built-in-funcs.html

documents "property" quite well.

I can't really agree that "quite good" documentation doesn't refer to
the use of property as a decorator. It's obvious that a ncessary upgrade
to the docs didn't happen (and we can all understand why, I am sure).


In my opinion property isn't really meant to be used as a decorator since
it's impossible to create a read-write property. The decorator pattern
doesn't really fit here.

What I agree is that it's not really defined what a "property" object
is and what its properties are. For that, documentation patches are
welcome.

Georg
Jun 28 '06 #12
Fredrik Lundh <fr*****@pythonware.com> wrote:
Sion Arrowsmith wrote:
What I've not seen documented anywhere is the:
@property
def fset(self, value):
...
idiom. It's not obvious from the documentation of the property
function that it can be used as a decorator like this.

probably because it cannot be used in that way: the "property" function
takes the *getter* as its first argument, so you can only use this for read-
only properties...


Ahem. Yes. What I obviously meant to write was:

What I've not seen documented anywhere is the:
@property
def fget(self):
...
idiom. [ ... ]

(As correctly written by someone else further upthread.) It is possible
to find it described by Googling, but the Cookbook (and python.org) hits
provide much more complicated general-purpose (ie setters as well)
property decorators.

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Jun 28 '06 #13

In article <11**********************@p79g2000cwp.googlegroups .com>,
"Gerard Flanagan" <gr********@yahoo.co.uk> writes:
|>
|> There are (unofficial) documentation wikis here:
|>
|> pytut.infogami.com
|> pyref.infogami.com
|> pyfaq.infogami.com

Thanks very much.

|> You might like to consider adding the information you perceive to be
|> lacking.

Consider it considered, but I have to start by understanding what is
supposed to happen and what does happen, precisely and in detail.
Regards,
Nick Maclaren.
Jun 28 '06 #14

In article <4Q*******@news.chiark.greenend.org.uk>,
Sion Arrowsmith <si***@chiark.greenend.org.uk> writes:
|>
|> Actually, there's an almost throw-away mention in
|> http://docs.python.org/ref/descriptor-invocation.html
|> which gives you what you need (although not, I have to say, in an
|> easily digestible form).

Thanks very much.

|> What I've not seen documented anywhere is the:
|> @property
|> def fset(self, value):
|> ...
|> idiom. It's not obvious from the documentation of the property
|> function that it can be used as a decorator like this. (cf.
|> classmethod and staticmethod.)

Most especially since it isn't working very well for me, and I am trying
to track down why. When I run:

class alf :
def pete (self) :
print "Inside pete\n"

b = alf()
b.pete()

class fred :
@property
def joe (self) :
print "Inside /joe\n"

a = fred()
a.joe()

I get:

Inside pete

Inside joe

Traceback (most recent call last):
File "crap.py", line 14, in <module>
a.joe()
TypeError: 'NoneType' object is not callable

VERY weird - I could understand it if I got the error and DIDN'T succeed
in the call ....
Regards,
Nick Maclaren.
Jun 28 '06 #15
Nick Maclaren wrote:
class fred :
@property
def joe (self) :
print "Inside /joe\n"

a = fred()
a.joe()

Traceback (most recent call last):
File "crap.py", line 14, in <module>
a.joe()
TypeError: 'NoneType' object is not callable

VERY weird - I could understand it if I got the error and DIDN'T succeed
in the call ....


a property looks like an attribute, not a method, so you're trying to call whatever
your "joe()" method returns.

(that's what "a function for getting an attribute value" in the property documentation
refers to).

</F>

Jun 28 '06 #16

In article <ma***************************************@python. org>,
"Fredrik Lundh" <fr*****@pythonware.com> writes:
|>
|> a property looks like an attribute, not a method, so you're trying to call whatever
|> your "joe()" method returns.

Well, yes, that was pretty obvious - but what was NOT obvious is why it
should do that for one of two identical methods.

|> (that's what "a function for getting an attribute value" in the property documentation
|> refers to).

Well, as joe is an attribute of the class fred, and the decorator is applied
to the declaration of joe within fred, I assumed that it referred to getting
joe from fred. That certainly doesn't appear to be the case, and I don't
see how it helps with my original request if not.
Regards,
Nick Maclaren.
Jun 28 '06 #17
Nick Maclaren wrote:
In article <4Q*******@news.chiark.greenend.org.uk>,
Sion Arrowsmith <si***@chiark.greenend.org.uk> writes:
|>
|> Actually, there's an almost throw-away mention in
|> http://docs.python.org/ref/descriptor-invocation.html
|> which gives you what you need (although not, I have to say, in an
|> easily digestible form).

Thanks very much.

|> What I've not seen documented anywhere is the:
|> @property
|> def fset(self, value):
|> ...
|> idiom. It's not obvious from the documentation of the property
|> function that it can be used as a decorator like this. (cf.
|> classmethod and staticmethod.)

Most especially since it isn't working very well for me, and I am trying
to track down why. When I run:

class alf :
def pete (self) :
print "Inside pete\n"

b = alf()
b.pete()

class fred :
@property
def joe (self) :
print "Inside /joe\n"

properties dont work properly on old-style classes (lookup 'new-style
classes' on python.org, in the documentation menu), hence the strange
behaviour you observe. Retry the same thing with s/class fred/class
fred(object)/
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 28 '06 #18
Nick Maclaren wrote:
|> a property looks like an attribute, not a method, so you're trying to call whatever
|> your "joe()" method returns.

Well, yes, that was pretty obvious - but what was NOT obvious is why it
should do that for one of two identical methods.
identical? you only applied @property to one of the methods, and then you're
surprised that only one of the methods were turned into a property?
|> (that's what "a function for getting an attribute value" in the property documentation
|> refers to).

Well, as joe is an attribute of the class fred, and the decorator is applied
to the declaration of joe within fred, I assumed that it referred to getting
joe from fred. That certainly doesn't appear to be the case


@property turns your "joe" method into a getter method for the (virtual) attribute
"joe". when you access the attribute, the getter method will be called. whatever
that method returns will be the attribute's value. that's what the documentation
says, and that's what your code is doing.

</F>

Jun 28 '06 #19
Bruno Desthuilliers wrote:
class fred :
@property
def joe (self) :
print "Inside /joe\n"

properties dont work properly on old-style classes (lookup 'new-style
classes' on python.org, in the documentation menu), hence the strange
behaviour you observe.


property getters work just fine on old-style classes (setters and deleters don't
work, but that's not what he's using).

</F>

Jun 28 '06 #20

In article <ma***************************************@python. org>,
"Fredrik Lundh" <fr*****@pythonware.com> writes:
|>
|> identical? you only applied @property to one of the methods, and then you're
|> surprised that only one of the methods were turned into a property?

I wasn't expecting EITHER to be turned INTO a property - I was expecting
both methods to be the same, but one would have non-default properties
attached to it.

|> @property turns your "joe" method into a getter method for the (virtual) attribute
|> "joe". when you access the attribute, the getter method will be called. whatever
|> that method returns will be the attribute's value.

Ah! That clarifies a lot.

|> that's what the documentation
|> says, and that's what your code is doing.

Er, no, it doesn't. What it says may well be COMPATIBLE with that, but
it is compatible with a good many other interpretations, too. Until and
unless you know what it means, you can't extract its meaning from its
words.
Regards,
Nick Maclaren.
Jun 28 '06 #21
Nick Maclaren schreef:

Most especially since it isn't working very well for me, and I am trying
to track down why. When I run:
class fred :
@property
def joe (self) :
print "Inside /joe\n"

a = fred()
a.joe()

I get:

Inside joe

Traceback (most recent call last):
File "crap.py", line 14, in <module>
a.joe()
TypeError: 'NoneType' object is not callable


Since joe is a property, you shouldn't access it as a method. This works:

a = fred()
a.joe

Inside joe
If you call it as a function, first the function is executed (printing
"Inside joe"), but then Python tries to call the return value of the
function, which is None.

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jun 28 '06 #22
Fredrik Lundh wrote:
Bruno Desthuilliers wrote:

class fred :
@property
def joe (self) :
print "Inside /joe\n"

properties dont work properly on old-style classes (lookup 'new-style
classes' on python.org, in the documentation menu), hence the strange
behaviour you observe.

property getters work just fine on old-style classes (setters and deleters don't
work, but that's not what he's using).


Thanks - I was too lazy to actually reread all the doc or derive this
from observation !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 28 '06 #23
Nick Maclaren wrote:
I wasn't expecting EITHER to be turned INTO a property - I was expecting
both methods to be the same, but one would have non-default properties
attached to it. |> that's what the documentation
|> says, and that's what your code is doing.

Er, no, it doesn't. What it says may well be COMPATIBLE with that, but
it is compatible with a good many other interpretations, too. Until and
unless you know what it means, you can't extract its meaning from its
words.


well, I completely fail to see how the following is compatible with the
interpretation "attaches a non-default property, but doesn't do anything
else":

property([fget[, fset[, fdel[, doc]]]]) => descriptor

Returns a property attribute for new-style classes (classes that
derive from object).

fget is a function for getting an attribute value, likewise fset is a
function for setting, and fdel a function for deleting, an
attribute. Typical use is to define a managed attribute x:

class C(object):
def __init__(self): self.__x = None
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")

</F>

Jun 28 '06 #24

In article <ma***************************************@python. org>,
Fredrik Lundh <fr*****@pythonware.com> writes:
|>
|> well, I completely fail to see how the following is compatible with the
|> interpretation "attaches a non-default property, but doesn't do anything
|> else":

Because I was using a decorator and defining an attribute directly.
But no matter - it is clear I had completely misunderstood the intent.
Regards,
Nick Maclaren.
Jun 28 '06 #25
Georg Brandl wrote:
In my opinion property isn't really meant to be used as a decorator since
it's impossible to create a read-write property. The decorator pattern
doesn't really fit here.

I agree that property isn't currently intended to be used as a decorator,
but it isn't actually *impossible* to create a read-write property using
decorators. Here is one way:

--------- props.py ----------------
from inspect import getouterframes, currentframe
import unittest

class property(property):
@classmethod
def get(cls, f):
locals = getouterframes(currentframe())[1][0].f_locals
prop = locals.get(f.__name__, property())
return cls(f, prop.fset, prop.fdel, prop.__doc__)

@classmethod
def set(cls, f):
locals = getouterframes(currentframe())[1][0].f_locals
prop = locals.get(f.__name__, property())
return cls(prop.fget, f, prop.fdel, prop.__doc__)

@classmethod
def delete(cls, f):
locals = getouterframes(currentframe())[1][0].f_locals
prop = locals.get(f.__name__, property())
return cls(prop.fget, prop.fset, f, prop.__doc__)

class PropTests(unittest.TestCase):
def test_setgetdel(self):
class C(object):
def __init__(self, colour):
self._colour = colour

@property.set
def colour(self, value):
self._colour = value

@property.get
def colour(self):
return self._colour

@property.delete
def colour(self):
self._colour = 'none'

inst = C('red')
self.assertEquals(inst.colour, 'red')
inst.colour = 'green'
self.assertEquals(inst._colour, 'green')
del inst.colour
self.assertEquals(inst._colour, 'none')

if __name__=='__main__':
unittest.main()
-----------------------------------
Jun 28 '06 #26
Duncan Booth wrote:
Georg Brandl wrote:
In my opinion property isn't really meant to be used as a decorator since
it's impossible to create a read-write property. The decorator pattern
doesn't really fit here.

I agree that property isn't currently intended to be used as a decorator,
but it isn't actually *impossible* to create a read-write property using
decorators. Here is one way:


Yes, I only wanted to say that it isn't possible by just using the builtin
property function as a decorator.

Georg
Jun 28 '06 #27
Nick Maclaren wrote:
In article <ma***************************************@python. org>,
"Fredrik Lundh" <fr*****@pythonware.com> writes:
|>
|> identical? you only applied @property to one of the methods, and then you're
|> surprised that only one of the methods were turned into a property?

I wasn't expecting EITHER to be turned INTO a property - I was expecting
both methods to be the same, but one would have non-default properties
attached to it.


That's another sign that property isn't intended to be used as a decorator.
Normally, decorators wrap functions with other functions. property doesn't
return a function but a descriptor object.

Georg
Jun 28 '06 #28
Georg Brandl a écrit :
Nick Maclaren wrote:
In article <ma***************************************@python. org>,
"Fredrik Lundh" <fr*****@pythonware.com> writes:
|>
|> identical? you only applied @property to one of the methods, and then you're
|> surprised that only one of the methods were turned into a property?

I wasn't expecting EITHER to be turned INTO a property - I was expecting
both methods to be the same, but one would have non-default properties
attached to it.

That's another sign that property isn't intended to be used as a decorator.
Normally, decorators wrap functions with other functions.


Normally, decorators take a function and return anything appropriate.
property doesn't
return a function but a descriptor object.


FWIW, function *are* descriptors (well, Python functions at least, cf
the recent thread about pyrex functions).
def fun(): pass .... fun.__get__ <method-wrapper object at 0x4041e1ec>

Jun 28 '06 #29
Georg Brandl a écrit :
Steve Holden wrote:

Thanks very much. And, what's more, I have even found its documentation!
Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.
Is it?

http://docs.python.org/lib/built-in-funcs.html

documents "property" quite well.


I can't really agree that "quite good" documentation doesn't refer to
the use of property as a decorator. It's obvious that a ncessary upgrade
to the docs didn't happen (and we can all understand why, I am sure).

In my opinion property isn't really meant to be used as a decorator since
it's impossible to create a read-write property. The decorator pattern
doesn't really fit here.


Making an attribute read-only is a common use case for properties, so
using property as a decorator in this case seems quite ok.
Jun 28 '06 #30
Bruno Desthuilliers a écrit :
Georg Brandl a écrit :

(snip)

That's another sign that property isn't intended to be used as a
decorator.
Normally, decorators wrap functions with other functions.

Normally, decorators take a function and return anything appropriate.
property doesn't
return a function but a descriptor object.
So do classmethod.
classmethod(fun).__get__ <method-wrapper object at 0x4041e1ec>
classmethod(fun)()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
Jun 28 '06 #31
Georg Brandl wrote:
Nick Maclaren wrote:
In article <ma***************************************@python. org>,
"Fredrik Lundh" <fr*****@pythonware.com> writes:
|>
|> identical? you only applied @property to one of the methods, and then you're
|> surprised that only one of the methods were turned into a property?

I wasn't expecting EITHER to be turned INTO a property - I was expecting
both methods to be the same, but one would have non-default properties
attached to it.

That's another sign that property isn't intended to be used as a decorator.
Normally, decorators wrap functions with other functions. property doesn't
return a function but a descriptor object.

OK, I still think the docs need updating, but to explain the above as
the reason *why* property's use as a decorator is not advised. Or is it
stylistically and semantically acceptable in the case of a read-only
property?

Would it make sense, in the single argument case, to default the doc
value to fget.__doc__ to support that use case, or should we just not
create read-only properties by using property as a decorator?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Love me, love my blog http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jun 29 '06 #32
Steve Holden wrote:
Georg Brandl wrote:
Nick Maclaren wrote:
In article <ma***************************************@python. org>,
"Fredrik Lundh" <fr*****@pythonware.com> writes:
|>
|> identical? you only applied @property to one of the methods, and then you're
|> surprised that only one of the methods were turned into a property?

I wasn't expecting EITHER to be turned INTO a property - I was expecting
both methods to be the same, but one would have non-default properties
attached to it.

That's another sign that property isn't intended to be used as a decorator.
Normally, decorators wrap functions with other functions. property doesn't
return a function but a descriptor object.

OK, I still think the docs need updating, but to explain the above as
the reason *why* property's use as a decorator is not advised. Or is it
stylistically and semantically acceptable in the case of a read-only
property?


I'm not the one to judge over that.
Would it make sense, in the single argument case, to default the doc
value to fget.__doc__ to support that use case, or should we just not
create read-only properties by using property as a decorator?


This is actually already the case in 2.5.

Georg
Jun 29 '06 #33
Georg Brandl wrote:
Steve Holden wrote: [...]
Would it make sense, in the single argument case, to default the doc
value to fget.__doc__ to support that use case, or should we just not
create read-only properties by using property as a decorator?

This is actually already the case in 2.5.

Sorry, haven't had much time for python-checkins lately. But this would
certainly argue that the decorator form for read-only properties is
accepted at some level.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Love me, love my blog http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jun 29 '06 #34
Steve Holden wrote:
Georg Brandl wrote:
Steve Holden wrote: [...]
Would it make sense, in the single argument case, to default the doc
value to fget.__doc__ to support that use case, or should we just not
create read-only properties by using property as a decorator?

This is actually already the case in 2.5.

Sorry, haven't had much time for python-checkins lately.


I didn't want to offend you, I must know since I implemented it myself ;)
But this would
certainly argue that the decorator form for read-only properties is
accepted at some level.


Yes, one could argue in this direction. I will ask on python-dev whether
an official hint should be added to the documentation.

Georg
Jun 29 '06 #35

Nick Maclaren wrote:
In article <ma***************************************@python. org>,
Robert Kern <ro*********@gmail.com> writes:
|> Nick Maclaren wrote:
|> > The way that I read it, Python allows only values (and hence types)
|> > to be immutable, and not class members. The nearest approach to the
|> > latter is to use the name hiding conventions.
|> >
|> > Is that correct?
|>
|> You can also make properties that don't allow writing.
|>
|> class Foo(object):
|>
|> def __init__(self, bar):
|> self._bar = bar
|>
|> @property
|> def bar(self):
|> return self._bar

Thanks very much. And, what's more, I have even found its documentation!
Whatsnew2.2. The 2.4.2 reference is, er, unhelpful.

One of Python's less-lovable attributes is the inscrutability of its
documentation :-(

But you knew that ....
Regards,
Nick Maclaren.


When I want to read about descriptors I use Raymond Hettingers "How To"
article which explains the matter quite fine:

http://users.rcn.com/python/download/Descriptor.htm

Jun 29 '06 #36
Georg Brandl wrote:
Steve Holden wrote:
Georg Brandl wrote:
Steve Holden wrote:

[...]

Would it make sense, in the single argument case, to default the doc
value to fget.__doc__ to support that use case, or should we just not
create read-only properties by using property as a decorator?
This is actually already the case in 2.5.

Sorry, haven't had much time for python-checkins lately.


I didn't want to offend you, I must know since I implemented it myself ;)
But this would
certainly argue that the decorator form for read-only properties is
accepted at some level.


Yes, one could argue in this direction. I will ask on python-dev whether
an official hint should be added to the documentation.


Okay, this is now documented in the trunk.

Georg
Jun 30 '06 #37
That is why I don't like the use of @property. Even though the
decorator is a nice short-hand notation, it is more confusing in my
oppinion. So someone is more likely still call the property as a
function when looking at:

class C:
@property
def data(self):
return 42

rather than if they saw:

class C:
def _data(self):
return 42
data=property(_data)

I personally I find the second case more readable, even though it is
longer.

-Nick
Fredrik Lundh wrote:
Nick Maclaren wrote:
|> a property looks like an attribute, not a method, so you're trying to call whatever
|> your "joe()" method returns.

Well, yes, that was pretty obvious - but what was NOT obvious is why it
should do that for one of two identical methods.


identical? you only applied @property to one of the methods, and then you're
surprised that only one of the methods were turned into a property?
|> (that's what "a function for getting an attribute value" in the property documentation
|> refers to).

Well, as joe is an attribute of the class fred, and the decorator is applied
to the declaration of joe within fred, I assumed that it referred to getting
joe from fred. That certainly doesn't appear to be the case


@property turns your "joe" method into a getter method for the (virtual) attribute
"joe". when you access the attribute, the getter method will be called. whatever
that method returns will be the attribute's value. that's what the documentation
says, and that's what your code is doing.

</F>


Jul 1 '06 #38

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: javac | last post by:
for better or worse, my free time is consumed by two Java series books from Sun: Java Platform Performance, 2000, by Wilson and Kesselman Effective Java, 2001, by Bloch 1.) opinions on these...
0
by: javac | last post by:
http://java.sun.com/docs/books/performance/ listing 7-11: --------------- If the following code is written in a package seperate from the Location class, it will now cause compile-time errors: ...
4
by: rb | last post by:
Hi This is a sample code I am working on. string a = "rb" string b = a Console.WriteLine(Object.ReferenceEquals(a,b)) In the above code, its printing true. I have a doubt on this output....
3
by: Terry Hancock | last post by:
Is there an *easy* way to make an object immutable in python? Or perhaps I should say "one obvious way to do it"? Oughtn't there to be one? I've found a thread on how to do this, which...
0
by: Tommy | last post by:
Our application uses BigDecimal, and BigDecimal is immutable. Immutability is certainly a good thing, but it also means that there are a lot more memory allocations (and collections). That's ok, we...
0
by: Simon Brunning | last post by:
2008/8/25 Hendrik van Rooyen <mail@microcorp.co.za>: You can indeed use ctypes to modify the value of a string - see <http://tinyurl.com/5hcnwl>. You can use it to crash the OS, too. My advice...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.