Skip to content

Grid: type annotations#825

Open
drothlis wants to merge 3 commits intomainfrom
grid-typing
Open

Grid: type annotations#825
drothlis wants to merge 3 commits intomainfrom
grid-typing

Conversation

@drothlis
Copy link
Contributor

@drothlis drothlis commented Jan 9, 2024

grid.py itself is now free of pylance warnings (apart from the type of Cell.data — see comment below).

TODO:

  • Check callers in keyboard.py.
  • Check callers in the unit tests.
  • Check how "T" renders in the generated documentation.
  • Check type of a Grid with no data — what is T?
  • itertools.chain(*g.data): Pylance says: Object of type "None" cannot be used as iterable value (reportOptionalIterable).

@drothlis
Copy link
Contributor Author

drothlis commented Jan 9, 2024

Note: Grid.Cell is now a dataclass instead of a namedtuple — could this be considered an API change?

Fixes this pylance warning about the Grid.__init__ use of TypeVar "T":

> TypeVar "T" appears only once in generic function

Unfortunately it now complains about the type of Grid.Cell.data:

> Type variable "T" has no meaning in this context

I believe this is a pylance bug. Note that I can't mark the `Grid.Cell`
class as `Generic[T]`, which I learned from pylance — it would complain
that TypeVar "T" is already in use by an outer scope.
@drothlis
Copy link
Contributor Author

drothlis commented Jan 9, 2024

Unfortunately it now complains about the type of Grid.Cell.data:

Type variable "T" has no meaning in this context

Copilot chat suggests:

One possible workaround is to define Cell as a separate class outside of Grid, and pass the type variable T as a parameter to both classes. Here's how you can do it:

@dataclasses.dataclass
class Cell(Generic[T]):
    index: int
    position: Position
    region: Region
    data: Optional[T]

class Grid(Generic[T]):
    # ...
    Cell: Type[Cell[T]]
    # ...

    def __init__(
        self,
        region: Region,
        cols: Optional[int] = None,
        rows: Optional[int] = None,
        data: Optional[Sequence[Sequence[T]]] = None,
    ):
        # ...
        self.Cell = Cell[T]

In this code, Cell is a generic class that takes a type variable T. The type of Cell.data is Optional[T], which means it can be either None or an instance of type T. When you create a Grid with a specific type, the Cell instances in that grid will also have data of that type.

Who knows if that'll work, but I won't bother.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant