googleapis / googleapis/python-genai
[Refactor] BaseApiClient: Adopt safe initialization pattern to simplify cleanup
- Dominant language
- Python
- Stars
- 4k
- Forks
- 1k
- Avg merge
- 2d 11h
- Merged PRs (30d)
- 40
Description
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()
Contributor guide
Assessment
This issue has not been assessed yet.