How should a python type hint require that a value has a given attribute?

前端 未结 3 1356
长情又很酷
长情又很酷 2021-01-03 09:31

Let\'s say I have a simple function like this:

def foo(a: Any):
    return a.bar + a.baz

I would lik

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 09:47

    Type hints can only refer to a class, so create an abstract class

    import abc
    
    class MyType(abc.ABC):
    
        @abc.abstractproperty
        def foo(self):
            pass
    
        @abc.abstractproperty
        def bar(self):
            pass
    

    And declare f(a: MyType)

提交回复
热议问题