Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8326921
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T00:55:52+00:00 2026-06-09T00:55:52+00:00

How can I efficiently in a proper pythonic pool/cache objects holding an expensive answer

  • 0

How can I efficiently in a proper pythonic pool/cache objects holding an expensive answer from the database?

My module contains following schematic code:

import sqlite3

db = sqlite3.connect(config.DB) # application shared database
db.row_factory = sqlite3.Row

class Foo:

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

    @property
    def bar(self):
        if not hasattr(self, '_bar'):
            row = db.execute(
                'SELECT bar FROM bars WHERE id=?', (self.id, )).fetchone()
            self._bar = row['bar'] if row else None
        return self._bar

Application is creating over its lifetime Foo objects to access some values bar in the database. The Foo.bar property represents an expensive operation, therefore the lazy processing. Instances of Foo class are not changing much at all, they are just a read-proxies for database stored data.

Now I realized, that Foo instances with the same id are created and destroyed quite often. Every time the object dies, the knowledge of Foo.bar is lost and has to be fetched from the database later again.

I figured two ways how I could deal with it, either pooling objects themselves:

class DBObject:

    _pool = {}

    def __new__(cls, *params, **key_params):        
        key = cls.__name__ + str(params) + str(key_params)
        if not key in DBObject._pool:
            self = object.__new__(cls, *params, **key_params)
            DBObject._pool[key] = self
        self = DBObject._pool[key]
        return self

class Foo(DBObject):
    ...

or their states:

class DBObject:

    _states = {}

    def __new__(cls, *params, **key_params):        
        self = object.__new__(cls, *params, **key_params)        
        key = cls.__name__ + str(params) + str(key_params)
        if not key in DBObject._states:
            DBObject._states[key] = {}            
        self.__dict__ = DBObject._states[key]
        return self

class Foo(DBObject):
    ...

Is there some better and more pythonic solution? Did I oversee something?

PS: I am Python beginner with Java/C++ background.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T00:55:53+00:00Added an answer on June 9, 2026 at 12:55 am

    I’d use a simple memoize decorator, here is a generic one:

    import functools
    
    def memoize(func):
        cache = {}
        sentinel = object()
    
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            key = (args, tuple(kwargs.items()))
            result = cache.get(key, sentinel)
            if result is not sentinel:
                return result
            result = func(*args, **kwargs)
            cache[key] = result
            return result       
        return wrapper
    

    You can use it to decorate the Foo class:

    @memoize
    class Foo:
    ...
    

    You can also apply the memoize decorator to the bar method, and clean it up a bit:

    @property
    @memoize
    def bar(self):
        row = db.execute('SELECT bar FROM bars where id=?', (self.id, )).fetchone()
        return row['bar'] if row else None
    

    Also new in Python3.2 is functools.lru_cache which has a number of nice features (clearing caches, keeping track of hit/miss stats, optional size and type checking)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am attempting to load customer objects from my database where the customer's name
How can I efficiently and easily sort a list of tuples without being sensitive
I would like some container that I can very efficiently append a variable amount
Can mysql handle a dataset of 50gb (only text) efficiently ? If not, what
Is there anything wrong with this code or can this be done more efficiently?
How can you make the efficient many-to-many -relation from fileID to Words and from
i want to run a routine backup of my database from my java application.
I've read a few sources on proper methods of bubbling a message out from
How can I most efficiently, inject string $A in between every two commas in
How can you select the most frequently occurring values in a MySQL database? Assuming

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.