aimclub / GOLEM

Graph Optimiser for Learning and Evolution of Models
https://thegolem.readthedocs.io
BSD 3-Clause "New" or "Revised" License
60 stars 7 forks source link

Fix variance specification for GraphFunction #270

Closed donRumata03 closed 6 months ago

donRumata03 commented 6 months ago

Resolves #264

As demonstrated by this code snippet:

from typing import Callable, TypeVar, Protocol

class SuperGraph:
    pass

class Graph(SuperGraph):
    pass

class SubGraph(Graph):
    pass

class Fitness:
    pass

G = TypeVar('G', bound=Graph, contravariant=True)
R = TypeVar('R', covariant=True)

# Instead of:
# G = TypeVar('G', bound=Graph, covariant=True)
# R = TypeVar('R', contravariant=True)

# Invariant is not versatile enough:
# G = TypeVar('G', bound=Graph)
# R = TypeVar('R')

class GraphFunction(Protocol[G, R]):
    def __call__(self, graph: G) -> R:
        ...

# Instead of:
# GraphFunction = Callable[[G], R]

def process_supergraph(graph: SuperGraph) -> int:
    return 42

def process_subgraph(graph: SubGraph) -> int:
    return 42

# This is valid: process_supergraph can be treated as GraphFunction[SubGraph, int]
graph_func: GraphFunction[SubGraph, int] = process_supergraph

# This is invalid: process_subgraph cannot be treated as GraphFunction[SuperGraph, int]
graph_func2: GraphFunction[Graph, int] = process_subgraph

Only the Protocol way defines the desired subtyping and passes mypy check.

While Callable is by default invariant over both its arguments.

codecov-commenter commented 6 months ago

Codecov Report

Attention: Patch coverage is 83.33333% with 1 lines in your changes are missing coverage. Please review.

Project coverage is 72.76%. Comparing base (68706be) to head (dad373a).

Files Patch % Lines
golem/core/optimisers/objective/objective.py 83.33% 1 Missing :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #270 +/- ## ========================================== - Coverage 72.88% 72.76% -0.12% ========================================== Files 140 140 Lines 8338 8340 +2 ========================================== - Hits 6077 6069 -8 - Misses 2261 2271 +10 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.