Search code examples
pythonpropertiestornado

What is the use of Python property decorator that returns an instance?


I saw a code as follows (from https://github.com/daydayfree/diggit/blob/master/model/model.py) :

from database import Database
...
class Model(object):
    @property
    def db(self): return Database()

    def insert(self, documents):
        return self.db.insert(self.table, documents)
...

The main aim for @property is to provide access to the methods in Database() instance, am I correct?

So can I rewrite it as:

from database import Database
...
class Model(object):
    def __init__(self):
        self.db = Database()

    def insert(self, documents):
        return self.db.insert(self.table, documents)

and

from database import Database
...
class Model(object):
    def db(self):
        return Database()

    def insert(self, documents):
        return self.db().insert(self.table, documents)
...

? If not, what are the differences between them?


Solution

  • There are differences...

    Method 1: property decorator

    class Model(object):
        @property
        def db(self): return Database() 
    
    o = Model()
    db1 = o.db  #a database instance. No brackets
    db2 = o.db  #another database instance
    o.db = foo  #error due to read only property
    

    Every time db is called it creates a new database instance.

    Method 2: db set on initialization

    class Model(object):
        def __init__(self):
            self.db = Database()
    
    o = Model()
    db1 = o.db  #a database instance
    db2 = o.db  #the same database instance
    o.db = foo  #works fine so long as foo is defined
    

    Every time db is accessed it returns the same database instance.

    Method 3: db as a function

    class Model(object):
        def db(self):
            return Database()
    
    o = Model()
    db1 = o.db()  #a database instance. note the brackets
    db2 = o.db()  #another database instance
    o.db = foo    #works fine so long as foo is defined
    

    Every time db is called it creates a new database instance.