Skip to content

Commit

Permalink
tests passing; hatch fmt ok; types core/ ok
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanLukes committed Aug 21, 2024
1 parent d2f4f8b commit 8361e84
Show file tree
Hide file tree
Showing 16 changed files with 117 additions and 145 deletions.
43 changes: 0 additions & 43 deletions scratch.py

This file was deleted.

6 changes: 3 additions & 3 deletions src/renkon/cli/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,9 @@ def score_fn(trait: AnyTrait) -> float:
)

# See the comment on sys.stdout's typeshed stubs for why this is valid (unless overriden).
if not isinstance(sys.stdout, TextIOWrapper):
msg = "sys.stdout is not a TextIOWrapper, cannot write CSV output."
raise RuntimeError(msg)
# if not isinstance(sys.stdout, TextIOWrapper):
# msg = "sys.stdout is not a TextIOWrapper, cannot write CSV output."
# raise RuntimeError(msg)

# Flush stdout to ensure output is written last, just in case.
sys.stderr.flush()
Expand Down
2 changes: 1 addition & 1 deletion src/renkon/core/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
]

from renkon.core.model.bitseries import BitSeries
from renkon.core.model.type import Type
from renkon.core.model.schema import Schema
from renkon.core.model.trait.kind import TraitKind
from renkon.core.model.trait.pattern import TraitPattern
from renkon.core.model.trait.result import TraitResult, TraitResultScore
from renkon.core.model.trait.sketch import TraitSketch
from renkon.core.model.trait.spec import TraitId, TraitSpec
from renkon.core.model.type import Type
from renkon.core.model.type_aliases import ColumnName, ColumnNames, ColumnType, ColumnTypes, ColumnTypeSet
8 changes: 3 additions & 5 deletions src/renkon/core/model/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from polars.type_aliases import SchemaDict
from pydantic import ConfigDict, RootModel

from renkon.core.model.type import polars_type_to_renkon_type, Type
from renkon.core.model.type import Type, polars_type_to_renkon_type
from renkon.core.model.type_aliases import ColumnName, ColumnNames


Expand All @@ -25,12 +25,10 @@ def __hash__(self) -> int:
return hash(tuple(self.root.items()))

@overload
def __getitem__(self, key: ColumnName) -> Type:
...
def __getitem__(self, key: ColumnName) -> Type: ...

@overload
def __getitem__(self, key: ColumnNames) -> Self:
...
def __getitem__(self, key: ColumnNames) -> Self: ...

def __getitem__(self, key: ColumnName | ColumnNames) -> Type | Self:
match key:
Expand Down
11 changes: 2 additions & 9 deletions src/renkon/core/model/trait/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,10 @@
#
# SPDX-License-Identifier: BSD-3-Clause

__all__ = [
"TraitId",
"TraitKind",
"TraitPattern",
"TraitSpec",
"TraitSketch",
"TraitResult"
]
__all__ = ["TraitId", "TraitKind", "TraitPattern", "TraitSpec", "TraitSketch", "TraitResult"]

from renkon.core.model.trait.kind import TraitKind
from renkon.core.model.trait.pattern import TraitPattern
from renkon.core.model.trait.result import TraitResult
from renkon.core.model.trait.sketch import TraitSketch
from renkon.core.model.trait.spec import TraitSpec, TraitId
from renkon.core.model.trait.spec import TraitId, TraitSpec
5 changes: 2 additions & 3 deletions src/renkon/core/model/trait/pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
from typing import TYPE_CHECKING, Annotated, Any, Literal, LiteralString, NamedTuple, TypeGuard

from annotated_types import Predicate
from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema as cs

if TYPE_CHECKING:
from collections.abc import Callable, Iterator

from pydantic import GetCoreSchemaHandler


def is_format_string(value: str) -> bool:
try:
Expand Down Expand Up @@ -127,5 +128,3 @@ def format(
mapping = {k: mapping.get(k, "{" + k + "}") for k in self.metavars + self.params}

return self.format_map(mapping)


5 changes: 3 additions & 2 deletions src/renkon/core/model/trait/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

type TypeFallbackTypevarStr = Annotated[Type | str, Field(union_mode="left_to_right")]


class TraitSpec(BaseModel):
"""
Model representing the descriptive identity of a trait.
Expand Down Expand Up @@ -46,8 +47,8 @@ class TraitSpec(BaseModel):
name: str
kind: TraitKind
pattern: TraitPattern
typevars: dict[str, Type] = dict()
typings: dict[str, TypeFallbackTypevarStr] = dict()
typevars: dict[str, Type] = {}
typings: dict[str, TypeFallbackTypevarStr] = {}

@property
def metavars(self) -> set[str]:
Expand Down
8 changes: 4 additions & 4 deletions src/renkon/core/model/type/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@
UnionType,
rk_bool,
rk_bottom,
rk_comparable,
rk_equatable,
rk_float,
rk_int,
rk_numeric,
rk_str,
rk_union,
rk_numeric,
rk_equatable,
rk_comparable,
)
from renkon.core.model.type.convert import renkon_type_to_polars_type, polars_type_to_renkon_type
from renkon.core.model.type.convert import polars_type_to_renkon_type, renkon_type_to_polars_type
4 changes: 3 additions & 1 deletion src/renkon/core/model/type/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def __hash__(self) -> int: ...

@classmethod
def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema:
schema = cls.__dict__.get('__pydantic_core_schema__')
schema = cls.__dict__.get("__pydantic_core_schema__")
if schema is not None:
return schema

Expand Down Expand Up @@ -336,6 +336,7 @@ def rk_union(*ts: Type) -> UnionType:

# region


# noinspection PyMethodMayBeStatic
class TreeToType(Transformer[Type]):
def type(self, type_: list[Type]):
Expand Down Expand Up @@ -371,4 +372,5 @@ def numeric(self, _) -> UnionType:
def paren(self, type_: list[Type]) -> Type:
return type_[0]


# endregion
9 changes: 6 additions & 3 deletions src/renkon/core/model/type/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
import polars as pl

from renkon.core.model.type import rk_int
from renkon.core.model.type.base import Type as RenkonType, rk_float, rk_str, rk_bool
from renkon.core.model.type.base import Type as RenkonType
from renkon.core.model.type.base import rk_bool, rk_float, rk_str


def polars_type_to_renkon_type(rk_ty: pl.PolarsDataType) -> RenkonType:
Expand All @@ -24,7 +25,8 @@ def polars_type_to_renkon_type(rk_ty: pl.PolarsDataType) -> RenkonType:
if rk_ty.is_(pl.Boolean):
return rk_bool

raise ValueError(f"Unsupported Polars data type: {rk_ty}")
msg = f"Unsupported Polars data type: {rk_ty}"
raise ValueError(msg)


def renkon_type_to_polars_type(rk_ty: RenkonType) -> pl.PolarsDataType:
Expand All @@ -44,4 +46,5 @@ def renkon_type_to_polars_type(rk_ty: RenkonType) -> pl.PolarsDataType:
if rk_ty.is_equal(rk_bool):
return pl.Boolean

raise ValueError(f"Unsupported Renkon data type: {rk_ty}")
msg = f"Unsupported Renkon data type: {rk_ty}"
raise ValueError(msg)
2 changes: 1 addition & 1 deletion src/renkon/core/model/type/grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
| "string" -> string
| "bool" -> bool
| "boolean" -> bool
special: "equatable" -> equatable
| "comparable" -> comparable
| "numeric" -> numeric
Expand Down
16 changes: 9 additions & 7 deletions src/renkon/core/traits/base.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# SPDX-FileCopyrightText: 2024-present Dylan Lukes <[email protected]>
#
# SPDX-License-Identifier: BSD-3-Clause
from typing import Protocol, final, ClassVar
from typing import ClassVar, Protocol, final

from renkon.core.model import TraitId, TraitKind, TraitPattern, TraitSpec, TraitSketch
from renkon.core.model.type import rk_numeric, rk_float, Type
from renkon.core.model import TraitId, TraitKind, TraitPattern, TraitSketch, TraitSpec
from renkon.core.model.type import Type, rk_float, rk_numeric


class Trait(Protocol):
Expand Down Expand Up @@ -35,10 +35,12 @@ def params(self) -> set[str]:
return set(self.pattern.params)

def sketch(self, **kwargs: dict[str, Type]) -> TraitSketch:
return TraitSketch.model_validate({
"trait": self.spec,
"metavar_bindings": kwargs,
})
return TraitSketch.model_validate(
{
"trait": self.spec,
"metavar_bindings": kwargs,
}
)


@final
Expand Down
25 changes: 15 additions & 10 deletions src/renkon/util/singleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@

import functools
from abc import ABCMeta
from collections.abc import Callable
from typing import Any, Concatenate
from typing import TYPE_CHECKING, Any, ClassVar, Concatenate

if TYPE_CHECKING:
from collections.abc import Callable


class _SingletonMeta(ABCMeta):
_instances: dict[type, Any] = {}
_instances: ClassVar[dict[type, Any]] = {}

def __call__(cls, *args: Any, **kwargs: Any):
if cls not in cls._instances:
cls._instances[cls] = super(_SingletonMeta, cls).__call__(*args, **kwargs)
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]


Expand All @@ -28,15 +30,16 @@ def get_instance(cls: type[Singleton]) -> Singleton:
# def singletonmethod[**P, R](_method: Callable[P, R]) -> Callable[P, R]:
# ...
# else:
class singletonmethod[T: Singleton, ** P, R]:
class singletonmethod[T: Singleton, **P, R]: # noqa: N801
"""Descriptor for a method which when called on the class, delegates to the singleton instance."""

method: Callable[Concatenate[T, P], R]
instance: T | None

def __init__(self, method: Callable[Concatenate[T, P], R], instance: T | None = None):
if not callable(method) and not hasattr(method, "__get__"):
raise TypeError(f"{method!r} is not callable or a descriptor")
msg = f"{method!r} is not callable or a descriptor"
raise TypeError(msg)
self.method = method
self.instance = instance

Expand All @@ -48,15 +51,16 @@ def __get__(self, instance: T | None, owner: type[T]) -> Callable[P, R]:

def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
if self.instance is None:
raise TypeError("singletonmethod instance is not set")
msg = "singletonmethod instance is not set"
raise TypeError(msg)
return self.method(self.instance, *args, **kwargs)

@property
def __isabstractmethod__(self):
return getattr(self.method, '__isabstractmethod__', False)
return getattr(self.method, "__isabstractmethod__", False)


class instancemethod[T, ** P, R]:
class instancemethod[T, **P, R]: # noqa: N801
method: Callable[Concatenate[T, P], R]
instance: T | None

Expand All @@ -71,7 +75,8 @@ def __get__(self, instance: T | None, owner: type[T]) -> Callable[P, R]:

def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
if self.instance is None:
raise TypeError("instancemethod called directly, not on instance")
msg = "instancemethod called directly, not on instance"
raise TypeError(msg)
return self.method(self.instance, *args, **kwargs)


Expand Down
2 changes: 1 addition & 1 deletion src/renkon/web/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# type: ignore
# TODO remove type ignore here
# TODO: remove type ignore here
from asyncio import sleep

import jinja2
Expand Down
Loading

0 comments on commit 8361e84

Please sign in to comment.