python-binance
python-binance copied to clipboard
fix(client): use proper exception instead of assert for US endpoints
Problem
The binance.us staking endpoints use assert statements for region validation:
assert self.tld == "us", "Endpoint only available on binance.us"
This is problematic because assert statements are completely disabled when running Python with the -O (optimize) flag, which is common in production deployments. When this happens the validation silently disappears and users get confusing API errors from Binance instead of a clear client-side error.
Solution
Added BinanceRegionException - a proper exception class that:
- Can't be disabled by interpreter flags
- Gives callers a specific exception type to catch
- Includes structured info (
required_tld,actual_tld,endpoint_name)
# Now users can handle this properly
try:
client.get_staking_asset_us()
except BinanceRegionException as e:
print(f"Wrong region: need {e.required_tld}, got {e.actual_tld}")
Changes
- Added
BinanceRegionExceptionto exceptions.py - Added
_require_tld()helper to BaseClient - Replaced 6 asserts in client.py and 6 in async_client.py
- Added tests covering all affected endpoints
Testing
All 15 new tests pass. Ran linting with ruff, no issues.
tests/test_region_exception.py - 15 passed