A Single Instance of an Object?

Ivan "Rambius" Ivanov rambiusparkisanius at gmail.com
Mon Mar 11 17:37:34 EDT 2024


On Mon, Mar 11, 2024 at 5:06 PM dn via Python-list
<python-list at python.org> wrote:
>
> 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...
>

Thank you for your suggestions. I will research them!

Regards
rambius


-- 
Tangra Mega Rock: http://www.radiotangra.com


More information about the Python-list mailing list