from functools import lru_cache
class Whatever:
pass
@lru_cache(maxsize=1)
def get_whatever():
return Whatever()
And use `get_whatever` as your interface to get the resource. from functools import lru_cache
class Whatever:
pass
@lru_cache(maxsize=1)
def get_whatever():
return Whatever()
And use `get_whatever` as your interface to get the resource.There's also code out there which replaces the cached module object with a class instance in top-level code! This is especially used to work around the prior lack of module-level `__getattr__` (and `__dir__`), added in 3.7 (https://peps.python.org/pep-0562/). But you might still need it if for some reason you want to hook into the lower-level `__getattribute__`. And Andrew Moffat's `sh` package still does this (https://github.com/amoffat/sh/blob/develop/sh.py#L3635) even though it now only declares support for 3.8 and above. (Perhaps there was simply no clear reason to change it.)
[0]: https://fastapi.tiangolo.com/advanced/events/#lifespan-funct...
[1]: https://asgi.readthedocs.io/en/latest/specs/lifespan.html#li...
I feel the blog post is a bunch of poorly thought through strawmen. I was browsing through the singleton example and I was wondering why would anyone use buggy code to implement something it clearly was not designed to implement.
The whole article is quite subpar. I was expecting idiomatic stuff that eliminated the need to implement something, like for example implementing singletons with modules and even getter functions, but there was none of that: just strawmen.
Really disappointing.