Skip to content

Commit 65fa7ff

Browse files
authored
chore(mypy): fix mypy lint errors (#540)
* chore(mypy): fix mypy lint errors * chore: add config for mypy
1 parent eb4bfc6 commit 65fa7ff

File tree

10 files changed

+39
-25
lines changed

10 files changed

+39
-25
lines changed

pyproject.toml

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ description = "With CocoIndex, users declare the transformation, CocoIndex creat
99
authors = [{ name = "CocoIndex", email = "[email protected]" }]
1010
readme = "README.md"
1111
requires-python = ">=3.11"
12-
dependencies = ["sentence-transformers>=3.3.1", "click>=8.1.8", "rich>=14.0.0", "python-dotenv>=1.1.0"]
12+
dependencies = [
13+
"sentence-transformers>=3.3.1",
14+
"click>=8.1.8",
15+
"rich>=14.0.0",
16+
"python-dotenv>=1.1.0",
17+
]
1318
license = "Apache-2.0"
1419
urls = { Homepage = "https://cocoindex.io/" }
1520

@@ -23,4 +28,9 @@ module-name = "cocoindex._engine"
2328
features = ["pyo3/extension-module"]
2429

2530
[project.optional-dependencies]
26-
test = ["pytest"]
31+
test = ["pytest"]
32+
33+
[tool.mypy]
34+
python_version = "3.11"
35+
# Disable for not as we have missing type annotations. See https://github.com/cocoindex-io/cocoindex/issues/539
36+
# strict = true

python/cocoindex/auth_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from dataclasses import dataclass
66
from typing import Generic, TypeVar
77

8-
from . import _engine
8+
from . import _engine # type: ignore
99
from .convert import dump_engine_object
1010

1111
T = TypeVar("T")

python/cocoindex/cli.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ def _load_user_app(app_target: str) -> types.ModuleType:
9090
raise ImportError(f"Could not create spec for file: {app_path}")
9191
module = importlib.util.module_from_spec(spec)
9292
sys.modules[spec.name] = module
93+
if spec.loader is None:
94+
raise ImportError(f"Could not create loader for file: {app_path}")
9395
spec.loader.exec_module(module)
9496
return module
9597
except (ImportError, FileNotFoundError, PermissionError) as e:
@@ -145,20 +147,21 @@ def ls(app_target: str | None):
145147
If APP_TARGET is omitted, lists all flows that have a persisted
146148
setup in the backend.
147149
"""
150+
persisted_flow_names = flow_names_with_setup()
148151
if app_target:
149152
app_ref = _get_app_ref_from_specifier(app_target)
150153
_load_user_app(app_ref)
151154

152155
current_flow_names = set(flow.flow_names())
153-
persisted_flow_names = set(flow_names_with_setup())
154156

155157
if not current_flow_names:
156158
click.echo(f"No flows are defined in '{app_ref}'.")
157159
return
158160

159161
has_missing = False
162+
persisted_flow_names_set = set(persisted_flow_names)
160163
for name in sorted(current_flow_names):
161-
if name in persisted_flow_names:
164+
if name in persisted_flow_names_set:
162165
click.echo(name)
163166
else:
164167
click.echo(f"{name} [+]")
@@ -170,13 +173,11 @@ def ls(app_target: str | None):
170173
click.echo(' [+]: Flows present in the current process, but missing setup.')
171174

172175
else:
173-
persisted_flow_names = sorted(flow_names_with_setup())
174-
175176
if not persisted_flow_names:
176177
click.echo("No persisted flow setups found in the backend.")
177178
return
178179

179-
for name in persisted_flow_names:
180+
for name in sorted(persisted_flow_names):
180181
click.echo(name)
181182

182183
@cli.command()

python/cocoindex/convert.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import uuid
88

99
from enum import Enum
10-
from typing import Any, Callable, get_origin
10+
from typing import Any, Callable, get_origin, Mapping
1111
from .typing import analyze_type_info, encode_enriched_type, is_namedtuple_type, TABLE_TYPES, KEY_FIELD_NAME
1212

1313

@@ -104,21 +104,20 @@ def _make_engine_struct_value_decoder(
104104

105105
src_name_to_idx = {f['name']: i for i, f in enumerate(src_fields)}
106106

107-
is_dataclass = dataclasses.is_dataclass(dst_struct_type)
108-
is_namedtuple = is_namedtuple_type(dst_struct_type)
109-
110-
if is_dataclass:
107+
parameters: Mapping[str, inspect.Parameter]
108+
if dataclasses.is_dataclass(dst_struct_type):
111109
parameters = inspect.signature(dst_struct_type).parameters
112-
elif is_namedtuple:
110+
elif is_namedtuple_type(dst_struct_type):
113111
defaults = getattr(dst_struct_type, '_field_defaults', {})
112+
fields = getattr(dst_struct_type, '_fields', ())
114113
parameters = {
115114
name: inspect.Parameter(
116115
name=name,
117116
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
118117
default=defaults.get(name, inspect.Parameter.empty),
119118
annotation=dst_struct_type.__annotations__.get(name, inspect.Parameter.empty)
120119
)
121-
for name in dst_struct_type._fields
120+
for name in fields
122121
}
123122
else:
124123
raise ValueError(f"Unsupported struct type: {dst_struct_type}")

python/cocoindex/flow.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from rich.text import Text
1818
from rich.tree import Tree
1919

20-
from . import _engine
20+
from . import _engine # type: ignore
2121
from . import index
2222
from . import op
2323
from . import setting

python/cocoindex/lib.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
import warnings
55
from typing import Callable, Any
66

7-
from . import _engine, flow, query, setting
7+
from . import _engine # type: ignore
8+
from . import flow, query, setting
89
from .convert import dump_engine_object
910

1011

python/cocoindex/op.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from .typing import encode_enriched_type, resolve_forward_ref
1212
from .convert import encode_engine_value, make_engine_value_decoder
13-
from . import _engine
13+
from . import _engine # type: ignore
1414

1515
class OpCategory(Enum):
1616
"""The category of the operation."""
@@ -101,7 +101,7 @@ def behavior_version(self):
101101

102102
class _WrappedClass(executor_cls, _Fallback):
103103
_args_decoders: list[Callable[[Any], Any]]
104-
_kwargs_decoders: dict[str, Callable[[str, Any], Any]]
104+
_kwargs_decoders: dict[str, Callable[[Any], Any]]
105105
_acall: Callable
106106

107107
def __init__(self, spec):
@@ -247,13 +247,13 @@ def __call__(self, *args, **kwargs):
247247
return fn(*args, **kwargs)
248248

249249
class _Spec(FunctionSpec):
250-
pass
250+
def __call__(self, *args, **kwargs):
251+
return fn(*args, **kwargs)
251252

252253
_Spec.__name__ = op_name
253254
_Spec.__doc__ = fn.__doc__
254255
_Spec.__module__ = fn.__module__
255256
_Spec.__qualname__ = fn.__qualname__
256-
_Spec.__wrapped__ = fn
257257

258258
_register_op_factory(
259259
category=OpCategory.FUNCTION,

python/cocoindex/query.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from . import flow as fl
66
from . import index
7-
from . import _engine
7+
from . import _engine # type: ignore
88

99
_handlers_lock = Lock()
1010
_handlers: dict[str, _engine.SimpleSemanticsQueryHandler] = {}

python/cocoindex/setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from . import flow
22
from . import setting
3-
from . import _engine
3+
from . import _engine # type: ignore
44

55
def sync_setup() -> _engine.SetupStatus:
66
flow.ensure_all_flows_built()

python/cocoindex/typing.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import types
66
import inspect
77
import uuid
8-
from typing import Annotated, NamedTuple, Any, TypeVar, TYPE_CHECKING, overload, Sequence, Protocol, Generic, Literal
8+
from typing import Annotated, NamedTuple, Any, TypeVar, TYPE_CHECKING, overload, Sequence, Generic, Literal, Protocol
99

1010
class VectorInfo(NamedTuple):
1111
dim: int | None
@@ -34,8 +34,11 @@ def __init__(self, key: str, value: Any):
3434
T_co = TypeVar('T_co', covariant=True)
3535
Dim_co = TypeVar('Dim_co', bound=int, covariant=True)
3636

37-
class Vector(Sequence[T_co], Generic[T_co, Dim_co], Protocol):
37+
class Vector(Protocol, Generic[T_co, Dim_co]):
3838
"""Vector[T, Dim] is a special typing alias for a list[T] with optional dimension info"""
39+
def __getitem__(self, index: int) -> T_co: ...
40+
def __len__(self) -> int: ...
41+
3942
else:
4043
class Vector: # type: ignore[unreachable]
4144
""" A special typing alias for a list[T] with optional dimension info """

0 commit comments

Comments
 (0)