Skip to content

Commit 8bc53bf

Browse files
hive-botclaude
andcommitted
feat: return None for absent API Pro usage details
Usage.api_key_character, speech_to_text_minutes and speech_to_speech_minutes are now Optional[Usage.Detail] and None when the response contains neither the count nor the limit. Usage.products skips entries that are not JSON objects instead of raising AttributeError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d3eb0f8 commit 8bc53bf

4 files changed

Lines changed: 65 additions & 25 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6262
it to `True` to add a "Translated by DeepL" watermark to `docx` and `pdf`
6363
output.
6464
- Added the API Pro usage fields to `Usage`: `api_key_character`,
65-
`speech_to_text_minutes` and `speech_to_speech_minutes` (as `Usage.Detail`),
66-
`start_time` and `end_time` (the billing period), and `products`, a list of
67-
`Usage.Product` objects with per-product usage. They are invalid or `None`
68-
when the response does not contain them.
65+
`speech_to_text_minutes` and `speech_to_speech_minutes` (as
66+
`Optional[Usage.Detail]`), `start_time` and `end_time` (the billing period),
67+
and `products`, a list of `Usage.Product` objects with per-product usage.
68+
They are `None` when the response does not contain them; `products` entries
69+
that are not JSON objects are skipped.
6970
- Added the Spoken Terms API (`/v3/spoken-terms`) to the `DeepLClient` class:
7071
`create_spoken_terms()`, `list_spoken_terms()`, `get_spoken_terms()`,
7172
`update_spoken_terms()`, `get_spoken_terms_entries()`,

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -781,8 +781,8 @@ if usage.document.valid:
781781
print(f"Document usage: {usage.document.count} of {usage.document.limit}")
782782
```
783783

784-
API Pro accounts also receive the following; for other accounts these usage
785-
subtypes are invalid and the other properties are `None`:
784+
API Pro accounts also receive the following; for other accounts, and whenever
785+
the response does not contain them, these properties are `None`:
786786

787787
- `api_key_character`: character usage of the API key making the request, as
788788
opposed to `character`, which covers the whole account,
@@ -800,7 +800,7 @@ usage = deepl_client.get_usage()
800800
if usage.start_time and usage.end_time:
801801
print(f"Billing period: {usage.start_time} to {usage.end_time}")
802802
print(f"Account characters: {usage.character.count} of {usage.character.limit}")
803-
if usage.api_key_character.valid:
803+
if usage.api_key_character and usage.api_key_character.valid:
804804
print(
805805
f"API key characters: {usage.api_key_character.count} of "
806806
f"{usage.api_key_character.limit}"

‎deepl/api_data.py‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ class Usage:
169169
checked individually.
170170
For API Pro accounts, api_key_character, speech_to_text_minutes,
171171
speech_to_speech_minutes, products, start_time and end_time provide
172-
further details; for other accounts they are invalid or None.
172+
further details; for other accounts they are None.
173173
The any_limit_reached property checks if for any usage type the amount used
174174
has reached the allowed amount.
175175
"""
@@ -279,16 +279,22 @@ def __init__(self, json: Optional[dict]):
279279
self._character = self.Detail(json, "character")
280280
self._document = self.Detail(json, "document")
281281
self._team_document = self.Detail(json, "team_document")
282-
self._api_key_character = self.Detail(json, "api_key_character")
283-
self._speech_to_text_minutes = self.Detail(
282+
self._api_key_character = self._optional_detail(
283+
json, "api_key_character"
284+
)
285+
self._speech_to_text_minutes = self._optional_detail(
284286
json, "speech_to_text_minutes"
285287
)
286-
self._speech_to_speech_minutes = self.Detail(
288+
self._speech_to_speech_minutes = self._optional_detail(
287289
json, "speech_to_speech_minutes"
288290
)
289291
products = json.get("products") if json else None
290292
self._products: Optional[List[Usage.Product]] = (
291-
[Usage.Product.from_json(p) for p in products]
293+
[
294+
Usage.Product.from_json(p)
295+
for p in products
296+
if isinstance(p, dict)
297+
]
292298
if isinstance(products, list)
293299
else None
294300
)
@@ -299,6 +305,18 @@ def __init__(self, json: Optional[dict]):
299305
json.get("end_time") if json else None
300306
)
301307

308+
@staticmethod
309+
def _optional_detail(
310+
json: Optional[dict], prefix: str
311+
) -> Optional["Usage.Detail"]:
312+
"""Returns the Detail for prefix, or None if the response contains
313+
neither its count nor its limit."""
314+
if not json or (
315+
f"{prefix}_count" not in json and f"{prefix}_limit" not in json
316+
):
317+
return None
318+
return Usage.Detail(json, prefix)
319+
302320
@property
303321
def any_limit_reached(self) -> bool:
304322
"""True if for the character, document or team document usage, the
@@ -340,22 +358,24 @@ def team_document(self) -> Detail:
340358
return self._team_document
341359

342360
@property
343-
def api_key_character(self) -> Detail:
361+
def api_key_character(self) -> Optional[Detail]:
344362
"""Returns character usage details for this API key, as opposed to
345-
character, which covers the whole account. Only valid for API Pro
346-
accounts."""
363+
character, which covers the whole account, or None if the response
364+
does not contain them (only present for API Pro accounts)."""
347365
return self._api_key_character
348366

349367
@property
350-
def speech_to_text_minutes(self) -> Detail:
351-
"""Returns speech-to-text usage details in minutes. Only valid for API
352-
Pro accounts."""
368+
def speech_to_text_minutes(self) -> Optional[Detail]:
369+
"""Returns speech-to-text usage details in minutes, or None if the
370+
response does not contain them (only present for API Pro
371+
accounts)."""
353372
return self._speech_to_text_minutes
354373

355374
@property
356-
def speech_to_speech_minutes(self) -> Detail:
357-
"""Returns speech-to-speech usage details in minutes. Only valid for
358-
API Pro accounts."""
375+
def speech_to_speech_minutes(self) -> Optional[Detail]:
376+
"""Returns speech-to-speech usage details in minutes, or None if the
377+
response does not contain them (only present for API Pro
378+
accounts)."""
359379
return self._speech_to_speech_minutes
360380

361381
@property

‎tests/offline/test_usage.py‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,16 +161,35 @@ def test_parses_free_usage_without_api_pro_fields(mocked):
161161

162162
assert usage.character.count == 20
163163
assert usage.character.limit == 500000
164-
assert not usage.api_key_character.valid
165-
assert usage.api_key_character.count is None
166-
assert not usage.speech_to_text_minutes.valid
167-
assert not usage.speech_to_speech_minutes.valid
164+
assert usage.api_key_character is None
165+
assert usage.speech_to_text_minutes is None
166+
assert usage.speech_to_speech_minutes is None
168167
assert usage.products is None
169168
assert usage.start_time is None
170169
assert usage.end_time is None
171170
assert str(usage) == "Usage this billing period:\nCharacters: 20 of 500000"
172171

173172

173+
def test_skips_non_object_product_entries(mocked):
174+
mocked.get(
175+
url("v2/usage"),
176+
json={
177+
"products": [
178+
"translate",
179+
None,
180+
{"product_type": "write", "api_key_unit_count": 3},
181+
]
182+
},
183+
)
184+
185+
usage = make_translator().get_usage()
186+
187+
assert usage.products is not None
188+
assert [
189+
(p.product_type, p.api_key_unit_count) for p in usage.products
190+
] == [("write", 3)]
191+
192+
174193
def test_ignores_unparseable_billing_period(mocked):
175194
mocked.get(
176195
url("v2/usage"),

0 commit comments

Comments
 (0)