@@ -84,6 +84,32 @@ def validate_decimal_places(value: Decimal, decimal_places: int, name: str) -> N
8484class Client (BaseApiClient [ElectricityTradingServiceStub ]):
8585 """Electricity trading client."""
8686
87+ _instances : dict [tuple [str , str | None ], "Client" ] = {}
88+
89+ def __new__ (
90+ cls , server_url : str , connect : bool = True , auth_key : str | None = None
91+ ) -> "Client" :
92+ """
93+ Create a new instance of the client or return an existing one if it already exists.
94+
95+ Args:
96+ server_url: The URL of the Electricity Trading service.
97+ connect: Whether to connect to the server immediately.
98+ auth_key: The API key for the authorization.
99+
100+ Returns:
101+ The client instance.
102+ """
103+ key = (server_url , auth_key )
104+
105+ # Check if an instance already exists for this key
106+ if key not in cls ._instances :
107+ # If not, create a new instance and store it in the cache
108+ instance = super (Client , cls ).__new__ (cls )
109+ cls ._instances [key ] = instance
110+
111+ return cls ._instances [key ]
112+
87113 def __init__ (
88114 self , server_url : str , connect : bool = True , auth_key : str | None = None
89115 ) -> None :
@@ -94,7 +120,11 @@ def __init__(
94120 connect: Whether to connect to the server immediately.
95121 auth_key: The API key for the authorization.
96122 """
97- super ().__init__ (server_url , ElectricityTradingServiceStub , connect = connect )
123+ if not hasattr (
124+ self , "_initialized"
125+ ): # Prevent re-initialization of existing instances
126+ super ().__init__ (server_url , ElectricityTradingServiceStub , connect = connect )
127+ self ._initialized = True
98128
99129 self ._gridpool_orders_streams : dict [
100130 tuple [int , GridpoolOrderFilter ],
0 commit comments