Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add interface class member to Benchmark class #20

Merged
merged 10 commits into from
Jan 24, 2024
21 changes: 20 additions & 1 deletion src/nnbench/types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Useful type interfaces to override/subclass in benchmarking workflows."""
from __future__ import annotations

import inspect
import os
from dataclasses import dataclass, field
from typing import Any, Callable, Generic, TypedDict, TypeVar
Expand Down Expand Up @@ -98,4 +99,22 @@ def __post_init__(self):
name = self.fn.__name__

super().__setattr__("name", name)
# TODO: Parse interface using `inspect`, attach to the class
super().__setattr__("interface", Interface.from_callable(self.fn))


@dataclass(frozen=True)
class Interface:
varnames: tuple[str, ...]
vartypes: tuple[type, ...]
varitems: tuple[tuple[str, inspect.Parameter], ...]
maxmynter marked this conversation as resolved.
Show resolved Hide resolved
defaults: dict[str, Any]

@classmethod
def from_callable(cls, fn: Callable) -> Interface:
sig = inspect.signature(fn)
return cls(
tuple(sig.parameters.keys()),
tuple(p.annotation for p in sig.parameters.values()),
tuple(sig.parameters.items()),
maxmynter marked this conversation as resolved.
Show resolved Hide resolved
{n: p.default for n, p in sig.parameters.items()},
)
32 changes: 32 additions & 0 deletions tests/test_benchmark_cls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import inspect

from nnbench import types


def test_interface_with_no_arguments():
def empty_function() -> None:
pass

interface = types.Interface.from_callable(empty_function)
assert interface.varnames == ()
assert interface.vartypes == ()
assert interface.varitems == ()
assert interface.defaults == {}


def test_interface_with_multiple_arguments():
def complex_function(a: int, b, c: str = "hello", d: float = 10.0) -> None: # type:ignore
pass

interface = types.Interface.from_callable(complex_function)
assert interface.varnames == ("a", "b", "c", "d")
assert interface.vartypes == (
int,
inspect._empty,
str,
float,
)

varitems = [(param.name, param.annotation) for name, param in interface.varitems]
assert varitems == [("a", int), ("b", inspect._empty), ("c", str), ("d", float)]
maxmynter marked this conversation as resolved.
Show resolved Hide resolved
assert interface.defaults == {"a": inspect._empty, "b": inspect._empty, "c": "hello", "d": 10.0}
Loading