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 type hints #56

Closed
nicrie opened this issue Jul 20, 2023 · 1 comment
Closed

add type hints #56

nicrie opened this issue Jul 20, 2023 · 1 comment
Labels
design Internal code structure documentation Improvements or additions to documentation

Comments

@nicrie
Copy link
Contributor

nicrie commented Jul 20, 2023

That should support code maintenance and documentation in the future.

In our case of subclasses we probably need TypeVar and Generic.

Here's an example:

from abc import ABC, abstractmethod
from typing import TypeVar, Generic

T = TypeVar('T')

class A(ABC, Generic[T]):
    @abstractmethod
    def method(self, input: T) -> T:
        pass

class B(A[int]):
    def method(self, input: int) -> int:
        # Implement the method specifically for ints
        pass

class C(A[float]):
    def method(self, input: float) -> float:
        # Implement the method specifically for floats
        pass

In this example, A is an abstract base class and uses a type variable T. It declares an abstract method method that takes an argument of type T and returns a value of type T. B and C inherit from A, specializing T to int and float respectively. Each of them implements method for their respective types.

This approach ensures that the subclasses B and C will work with the specific types you want (int and float respectively), while maintaining the generality of the base class A.

If we want to ensure that A should only be instantiated with certain types, we can add constraints to the TypeVar:

T = TypeVar('T', int, float)

With this, T can only be int or float, and trying to create a class that inherits from A[str] for example, would result in a type error.

@nicrie nicrie added documentation Improvements or additions to documentation design Internal code structure labels Jul 20, 2023
@nicrie
Copy link
Contributor Author

nicrie commented Oct 24, 2023

fixed by #91

@nicrie nicrie closed this as completed Oct 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
design Internal code structure documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant