googleapis / googleapis/python-genai

[Refactor] BaseApiClient: Adopt safe initialization pattern to simplify cleanup

Aperta
#2,023 1 commento 1 reazione 1 assegnatario Rivendicata da @Venkaiahbabuneelam Vedi su GitHub
priority: p2 type: bug
Lingua principale
Python
Stelle
4k
Fork
1k
Merge medio
2g 12h
PR unite (30g)
41

Descrizione

The current `BaseApiClient.__init__` interleaves validation with instantiation, leaving objects in a non-deterministic partial state if initialization fails early (e.g. `ValueError`). This forces `__del__` and cleanup methods to rely on brittle `try...except AttributeError` blocks to avoid crashing on missing attributes like `_http_options`.

We should refactor `__init__` to pre-declare all instance attributes to `None` immediately upon entry. This guarantees a deterministic state, enabling `close()` and `aclose()` to replace defensive error handling with simple, robust existence checks (e.g. `if self._client`).

```python
# Current state (init fails early -> close() crashes)
def __init__(self, ...):
if bad_input: raise ValueError()
self._client = Client()

def close(self):
self._client.close() # crash: attribute error

# Interim fix (prevents crash but brittle)
def close(self):
try:
self._client.close()
except AttributeError: # defensive coding required
return

# Desired state
def __init__(self, ...):
self._client = None # pre-declare

if bad_input: raise ValueError() # validate

self._client = Client() # instantiate

def close(self):
if self._client: # simple existence check
self._client.close()

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.