Skip to content

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

@chidifrank

Description

@chidifrank

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).

# 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()

Metadata

Metadata

Assignees

Labels

type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions