Sujet : Re: A Single Instance of an Object?
De : PythonList (at) *nospam* DancesWithMice.info (dn)
Groupes : comp.lang.pythonDate : 11. Mar 2024, 22:03:01
Autres entêtes
Organisation : DWM
Message-ID : <mailman.87.1710190996.3452.python-list@python.org>
References : 1 2
User-Agent : Mozilla Thunderbird
Good question Rambius!
On 12/03/24 09:53, Ivan "Rambius" Ivanov via Python-list wrote:
Hello,
I am refactoring some code and I would like to get rid of a global
variable. Here is the outline:
import subprocess
CACHE = {}
First thought: don't reinvent-the-wheel, use lru_cache (
https://docs.python.org/3/library/functools.html)
The global cache variable made unit testing of the lookup(key) method
clumsy, because I have to clean it after each unit test. I refactored
it as:
class Lookup:
def __init__(self):
self.cache = {}
Change "cache" to be a class-attribute (it is currently an instance.
Then, code AFTER the definition of Lookup can refer to Lookup.cache, regardless of instantiation, and code within Lookup can refer to self.cache as-is...
-- Regards,=dn