unpythonic use of property()?

J Kenneth King james at agentultra.com
Fri Apr 17 19:21:02 CEST 2009



class MyInterface(object):

    def __get_id(self):
        return self.__id

    id = property(fget=__get_id)

    def __init__(self, id, foo):
        self.__id = id
        self.foo = foo

class MyInterface2(object):

    def __init__(self, id, foo):
        self._id = id
        self.foo = foo

    def id(self):
        return self._id


The situation is that an API to an external resource must enforce
consistency with the resource's expectations of data (ie: ID's must be

The Python docs clearly show the use of the property() decorator in both
the example classes shown here. Both ensure that an assignment to the
class objects' 'id' attribute will raise an AttributeError
exception. Both will satisfy the requirements.

I assume we all know what the implementation differences are between the
two examples here. What I am curious about is what use case would the
MyInterface example have? My guess is that it's added protection for
attribute names on objects generated from factories or generators. I'd
like a more concrete explanation from someone who has encountered a
scenario where it was required.

I was recently informed that it was 'unpythonic' and have since been a
little confused by the term. I've heard it bandied about before but
never paid much attention. What is 'unpythonic'? What about this example
is unpythonic?

More information about the Python-list mailing list