Skip to content

Commit 2e885f0

Browse files
wilsonfreitasclaude
andcommitted
Add complete type annotations for mypy strict compliance (Phase 3)
- bcb/utils.py: annotate Date comparison methods with proper parameter types - bcb/sgs/__init__.py: fix _get_url_and_payload return type to tuple[str, dict], add Optional[str] for freq param, use Mapping for SGSCodeInput covariance, fix SGSCode.__repr__ (self.code -> self.value) - bcb/currency.py: annotate CACHE, fix _currency_url param type, add Optional import, raise CurrencyNotFoundError in _get_currency_id instead of returning NaN - bcb/odata/framework.py: annotate all classes and methods, add Self for chainable ODataQuery methods, add fullname attr to ODataEntitySet, use typing_extensions.Self - bcb/odata/api.py: annotate all methods, declare BASE_URL on BaseODataAPI, rename K -> SERVICE_KEY on subclasses, collect() -> pd.DataFrame - pyproject.toml: add types-requests to dev dependencies poetry run mypy bcb/ exits with 0 errors across 9 source files. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 8c066c4 commit 2e885f0

7 files changed

Lines changed: 215 additions & 171 deletions

File tree

bcb/currency.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import warnings
33
from datetime import date, timedelta
44
from io import BytesIO, StringIO
5-
from typing import List, Union
5+
from typing import List, Optional, Union
66

77
import numpy as np
88
import pandas as pd
@@ -17,7 +17,7 @@
1717
"""
1818

1919

20-
def _currency_url(currency_id: str, start_date: DateInput, end_date: DateInput) -> str:
20+
def _currency_url(currency_id: int, start_date: DateInput, end_date: DateInput) -> str:
2121
start_date = Date(start_date)
2222
end_date = Date(end_date)
2323
return (
@@ -27,7 +27,7 @@ def _currency_url(currency_id: str, start_date: DateInput, end_date: DateInput)
2727
)
2828

2929

30-
CACHE = dict()
30+
CACHE: dict[str, pd.DataFrame] = dict()
3131

3232

3333
def _currency_id_list() -> pd.DataFrame:
@@ -100,11 +100,17 @@ def _get_currency_id(symbol: str) -> int:
100100
id_list = _currency_id_list()
101101
all_currencies = get_currency_list()
102102
x = pd.merge(id_list, all_currencies, on=["name"])
103-
return np.max(x.loc[x["symbol"] == symbol, "id"])
103+
matches = x.loc[x["symbol"] == symbol, "id"]
104+
if matches.empty:
105+
raise CurrencyNotFoundError(f"Unknown currency symbol: {symbol}")
106+
return int(matches.max())
104107

105108

106-
def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.DataFrame:
107-
cid = _get_currency_id(symbol)
109+
def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> Optional[pd.DataFrame]:
110+
try:
111+
cid = _get_currency_id(symbol)
112+
except CurrencyNotFoundError:
113+
return None
108114
url = _currency_url(cid, start_date, end_date)
109115
res = requests.get(url)
110116

bcb/odata/api.py

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from typing import Any, Optional
12
from .framework import (
23
ODataEntitySet,
34
ODataFunctionImport,
@@ -13,10 +14,10 @@
1314

1415

1516
class EndpointMeta(type):
16-
def __init__(self, *args, **kwargs):
17+
def __init__(self, *args: Any, **kwargs: Any) -> None:
1718
super().__init__(*args, **kwargs)
1819

19-
def __call__(self, *args):
20+
def __call__(self, *args: Any) -> Any:
2021
obj = super().__call__(*args)
2122
entity = args[0]
2223
if isinstance(entity, ODataEntitySet):
@@ -29,18 +30,18 @@ def __call__(self, *args):
2930

3031

3132
class EndpointQuery(ODataQuery):
32-
_DATE_COLUMN_NAMES_BY_ENDPOINT = {
33+
_DATE_COLUMN_NAMES_BY_ENDPOINT: dict[str, dict[str, str]] = {
3334
"IfDataCadastro": {"Data": "%Y%m"}
3435
}
35-
_DATE_COLUMN_NAMES = {
36+
_DATE_COLUMN_NAMES: set[str] = {
3637
"Data",
3738
"dataHoraCotacao",
3839
"InicioPeriodo",
3940
"FimPeriodo",
4041
"DataVigencia",
4142
}
4243

43-
def collect(self):
44+
def collect(self) -> pd.DataFrame:
4445
raw_data = super().collect()
4546
data = pd.DataFrame(raw_data["value"])
4647
if not self._raw:
@@ -65,7 +66,7 @@ class Endpoint(metaclass=EndpointMeta):
6566
:py:meth:`bcb.odata.api.BaseODataAPI.get_endpoint` das classes que herdam
6667
:py:class:`bcb.odata.api.BaseODataAPI`.
6768
"""
68-
def __init__(self, entity, url):
69+
def __init__(self, entity: Any, url: str) -> None:
6970
"""
7071
Construtor da classe Endpoint.
7172
@@ -80,7 +81,7 @@ def __init__(self, entity, url):
8081
self._entity = entity
8182
self._url = url
8283

83-
def get(self, *args, **kwargs):
84+
def get(self, *args: Any, **kwargs: Any) -> pd.DataFrame:
8485
"""
8586
Executa a consulta na API OData e retorna o resultado.
8687
@@ -120,7 +121,7 @@ def get(self, *args, **kwargs):
120121
_query.reset()
121122
return data
122123

123-
def query(self):
124+
def query(self) -> EndpointQuery:
124125
"""
125126
Retorna uma instância de EndpointQuery através da qual se construirá a consulta na API OData.
126127
@@ -138,13 +139,15 @@ class BaseODataAPI:
138139
Essa classe não deve ser acessada diretamente.
139140
"""
140141

141-
def __init__(self):
142+
BASE_URL: str
143+
144+
def __init__(self) -> None:
142145
"""
143146
BaseODataAPI construtor
144147
"""
145148
self.service = ODataService(self.BASE_URL)
146149

147-
def describe(self, endpoint=None):
150+
def describe(self, endpoint: Optional[str] = None) -> None:
148151
"""
149152
Mostra a descrição de uma API ou de um *endpoint*
150153
específico.
@@ -166,7 +169,7 @@ def describe(self, endpoint=None):
166169
else:
167170
self.service.describe()
168171

169-
def get_endpoint(self, endpoint):
172+
def get_endpoint(self, endpoint: str) -> Endpoint:
170173
"""
171174
Obtem o *endpoint*
172175
@@ -200,7 +203,7 @@ class ODataAPI(BaseODataAPI):
200203
não possuem implementação específica.
201204
"""
202205

203-
def __init__(self, url):
206+
def __init__(self, url: str) -> None:
204207
"""
205208
Parameters
206209
----------
@@ -411,8 +414,8 @@ class TarifasBancariasPorInstituicaoFinanceira(BaseODataAPI):
411414
cobradas por instituições financeiras, por Segmento e por Instituição.
412415
"""
413416

414-
K = "Informes_ListaTarifasPorInstituicaoFinanceira"
415-
BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
417+
SERVICE_KEY = "Informes_ListaTarifasPorInstituicaoFinanceira"
418+
BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
416419

417420

418421
class TarifasBancariasPorServico(BaseODataAPI):
@@ -424,8 +427,8 @@ class TarifasBancariasPorServico(BaseODataAPI):
424427
por serviço.
425428
"""
426429

427-
K = "Informes_ListaValoresDeServicoBancario"
428-
BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
430+
SERVICE_KEY = "Informes_ListaValoresDeServicoBancario"
431+
BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
429432

430433

431434
class PostosAtendimentoEletronicoPorInstituicaoFinanceira(BaseODataAPI):
@@ -437,8 +440,8 @@ class PostosAtendimentoEletronicoPorInstituicaoFinanceira(BaseODataAPI):
437440
pelo Banco Central.
438441
"""
439442

440-
K = "Informes_PostosDeAtendimentoEletronico"
441-
BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
443+
SERVICE_KEY = "Informes_PostosDeAtendimentoEletronico"
444+
BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
442445

443446

444447
class PostosAtendimentoCorrespondentesPorInstituicaoFinanceira(BaseODataAPI):
@@ -451,8 +454,8 @@ class PostosAtendimentoCorrespondentesPorInstituicaoFinanceira(BaseODataAPI):
451454
descrito na Resolução 3.954.
452455
"""
453456

454-
K = "Informes_Correspondentes"
455-
BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
457+
SERVICE_KEY = "Informes_Correspondentes"
458+
BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
456459

457460

458461
class EstatisticasSTR(BaseODataAPI):
@@ -464,8 +467,8 @@ class EstatisticasSTR(BaseODataAPI):
464467
mantidas pelos participantes no Banco Central.
465468
"""
466469

467-
K = "STR"
468-
BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
470+
SERVICE_KEY = "STR"
471+
BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
469472

470473

471474
class DinheiroCirculacao(BaseODataAPI):
@@ -478,8 +481,8 @@ class DinheiroCirculacao(BaseODataAPI):
478481
Real (símbolos : R$, BRL).
479482
"""
480483

481-
K = "mecir_dinheiro_em_circulacao"
482-
BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
484+
SERVICE_KEY = "mecir_dinheiro_em_circulacao"
485+
BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
483486

484487

485488
# /Informes_Ouvidorias/versao/v1/odata/

0 commit comments

Comments
 (0)