Skip to content

Instantly share code, notes, and snippets.

@gmaze
Created October 24, 2025 10:30
Show Gist options
  • Select an option

  • Save gmaze/4a08b108e9bc5820c623c58b98cbcfc4 to your computer and use it in GitHub Desktop.

Select an option

Save gmaze/4a08b108e9bc5820c623c58b98cbcfc4 to your computer and use it in GitHub Desktop.
A python class that will be instantiated only once
# For the class:
from typing import Any, Callable
from functools import lru_cache
import inspect
# Things to be used only once
from argopy.stores import httpstore
from argopy.options import OPTIONS
class MyPattern:
"""A class that will be instantiated only once to avoid multiple httpstore creation
Examples
--------
.. code-block:: python
p1 = MyPattern()
p2 = MyPattern()
id(p1) == id(p2)
p1._fs == p2._fs
p1.open_json(...)
"""
uid : str = None
"""Unique instance ID"""
_fs: Any = None
_instance: 'MyPattern | None' = None
_initialized: bool = False
def __new__(cls, *args: Any, **kwargs: Any) -> 'MyPattern':
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, *args, **kwargs) -> None:
if not self._initialized:
self._fs = httpstore(cache=kwargs.get("cache", True), cachedir=kwargs.get("cachedir", OPTIONS["cachedir"]), timeout=kwargs.get("timeout", OPTIONS["api_timeout"]))
self._initialized = True
self.uid = id(self)
def __setattr__(self, attr, value):
"""Set attribute value, with read-only after instantiation policy for public attributes"""
if attr in [key for key in self.__dir__() if key[0] != '_'] and inspect.stack()[1][3] != '__init__':
raise AttributeError(f"'{attr}' is read-only after instantiation.")
self.__dict__[f"{attr}"] = value
def __repr__(self):
props = [key for key in self.__dir__() if key[0] != '_' and not isinstance(getattr(self, key), Callable)]
props = sorted(props)
props_str = [f"{prop}={getattr(self, prop)}" for prop in props]
return f"MyPattern({', '.join(props_str)})"
@lru_cache
def open_json(self, *args, **kwargs):
return self._fs.open_json(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment