Skip to content

Commit

Permalink
typing
Browse files Browse the repository at this point in the history
  • Loading branch information
Christian-B committed Oct 17, 2024
1 parent a789159 commit 102d093
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 15 deletions.
8 changes: 5 additions & 3 deletions spinn_utilities/logger_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from spinn_utilities.log import FormatAdapter

_already_issued = set()


def warn_once(logger, msg):
def warn_once(logger: FormatAdapter, msg: str) -> None:
"""
Write a warning message to the given logger where that message should only
be written to the logger once.
Expand All @@ -32,7 +34,7 @@ def warn_once(logger, msg):
logger.warning(msg)


def error_once(logger, msg):
def error_once(logger: FormatAdapter, msg: str) -> None:
"""
Write an error message to the given logger where that message should only
be written to the logger once.
Expand All @@ -49,7 +51,7 @@ def error_once(logger, msg):
logger.error(msg)


def reset():
def reset() -> None:
"""
Clear the store of what messages have already been seen.
Expand Down
6 changes: 3 additions & 3 deletions spinn_utilities/ordered_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def __init__(self, iterable: Optional[Iterable[T]] = None):
if iterable is not None:
self.update(iterable)

def add(self, value: T):
def add(self, value: T) -> None:
if value not in self._map:
self._map[value] = None

def discard(self, value: T):
def discard(self, value: T) -> None:
if value in self._map:
self._map.pop(value)

Expand Down Expand Up @@ -72,7 +72,7 @@ def __len__(self) -> int:
def __contains__(self, key: Any) -> bool:
return key in self._map

def update(self, iterable: Iterable[T]):
def update(self, iterable: Iterable[T]) -> None:
"""
Updates the set by adding each item in order
Expand Down
1 change: 0 additions & 1 deletion spinn_utilities/progress_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
from typing_extensions import Literal, Self

from spinn_utilities.config_holder import get_config_bool
from spinn_utilities.exceptions import SpiNNUtilsException
from spinn_utilities.log import FormatAdapter
from spinn_utilities.overrides import overrides
from spinn_utilities import logger_utils
Expand Down
17 changes: 12 additions & 5 deletions spinn_utilities/require_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Any, Callable, Dict, List, Type

from spinn_utilities.abstract_base import AbstractBase


class _RequiresSubclassTypeError(TypeError):
"""
Expand All @@ -22,7 +26,8 @@ class _RequiresSubclassTypeError(TypeError):
"""


def require_subclass(required_class):
def require_subclass(required_class: Type[AbstractBase]
) -> Callable[[Type[AbstractBase]], Type[AbstractBase]]:
"""
Decorator that arranges for subclasses of the decorated class to
require that they are also subclasses of the given class.
Expand Down Expand Up @@ -52,20 +57,22 @@ class AbstractVirtual(object):
# without it, some very weird interactions with meta classes happen and I
# really don't want to debug that stuff.

def decorate(target_class):
def decorate(target_class: Type[AbstractBase]) -> Type[AbstractBase]:
# pylint: disable=unused-variable
__class__ = target_class # @ReservedAssignment # noqa: F841

def __init_subclass__(cls, allow_derivation=False, **kwargs):
def __init_subclass__(
cls: Type[AbstractBase], allow_derivation: bool = False,
**kwargs: Dict[str, Any]) -> None:
if not issubclass(cls, required_class) and not allow_derivation:
raise _RequiresSubclassTypeError(
f"{cls.__name__} must be a subclass "
f"of {required_class.__name__} and the derivation was not "
"explicitly allowed with allow_derivation=True")
try:
super().__init_subclass__(**kwargs)
super().__init_subclass__(**kwargs) # type: ignore[misc]
except _RequiresSubclassTypeError:
super().__init_subclass__(
super().__init_subclass__( # type: ignore[misc]
allow_derivation=allow_derivation, **kwargs)

setattr(target_class, '__init_subclass__',
Expand Down
12 changes: 9 additions & 3 deletions spinn_utilities/safe_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from types import CodeType, ModuleType
from typing import Any, Dict, Union
from typing_extensions import Buffer


class SafeEval(object):
"""
Expand Down Expand Up @@ -42,7 +46,7 @@ class SafeEval(object):
"""
__slots__ = ["_environment"]

def __init__(self, *args, **kwargs):
def __init__(self, *args: ModuleType, **kwargs: Dict[str, Any]):
"""
:param args:
The symbols to use to populate the global reference table.
Expand All @@ -58,13 +62,15 @@ def __init__(self, *args, **kwargs):
symbols (e.g., constants in numpy) do not have names that we can
otherwise look up easily.
"""
env = {}
env: Dict[Any, Any] = {}
item: ModuleType
for item in args:
env[item.__name__] = item
env.update(kwargs)
self._environment = env

def eval(self, expression, **kwargs):
def eval(self, expression: Union[str, Buffer, CodeType],
**kwargs: Dict[str, Any]) -> Any:
"""
Evaluate an expression and return the result.
Expand Down

0 comments on commit 102d093

Please sign in to comment.