How do I correctly add type-hints to Mixin classes?

后端 未结 5 1812
梦谈多话
梦谈多话 2021-02-13 02:33

Consider the following example. The example is contrived but illustrates the point in a runnable example:

class MultiplicatorMixin:

    def multiply(self, m: in         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 03:06

    In addition to good answers mentioned above. My use case - mixins to be used in tests.

    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)
    

提交回复
热议问题