Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Last active September 19, 2019 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barseghyanartur/dc5d83665c94f4215da55ab9c0ca6896 to your computer and use it in GitHub Desktop.
Save barseghyanartur/dc5d83665c94f4215da55ab9c0ca6896 to your computer and use it in GitHub Desktop.
Typing mixins

As proposed by Guido van Rossum himself here:

from typing import *
T = TypeVar('T')

class Base:
    fit: Callable

class Foo(Base):
    def fit(self, arg1: int) -> Optional[str]:
        pass

class Bar(Foo):
    def fit(self, arg1: float) -> str:
        pass    

Thus, when it comes to a mixin, it could look as follows:

class UsefulMixin:

    assertLess: Callable
    assertIn: Callable
    assertIsNotNone: Callable

    def something_useful(self, key, value):
        self.assertIsNotNone(key)
        self.assertLess(key, 10)
        self.assertIn(value, ['Alice', 'in', 'Wonderland']


class AnotherUsefulMixin:

    assertTrue: Callable
    assertFalse: Callable
    assertIsNone: Callable

    def something_else_useful(self, val, foo, bar):
        self.assertTrue(val)
        self.assertFalse(foo)
        self.assertIsNone(bar)  

And our final class would look as follows:

class TestSomething(unittest.TestCase, UsefulMixin, AnotherUsefulMixin):

    def test_something(self):
        self.something_useful(10, 'Alice')
        self.something_else_useful(True, False, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment