rodi icon indicating copy to clipboard operation
rodi copied to clipboard

Use `Self` type for `Container`

Open sobolevn opened this issue 1 year ago • 0 comments

I've improved the self annotations for the Container type. So, here's how it works:

  1. There's a dedicated Self type in typing and typing_extensions that we cannot use here, because typing_extensions is not required for python>=3.9 and Self was only added to typing in 3.11 or 3.12
  2. Here's the difference between -> "Container" and -> _ContainerSelf that I am using now:
from typing import TypeVar

_S = TypeVar('_S', bound='My')

class My:
    def with_s(self: _S) -> _S:
        return self
        
    def with_annotation(self) -> 'My':
        return self
        
class Child(My): ...

reveal_type(Child().with_s())
# N: Revealed type is "__main__.Child"

reveal_type(Child().with_annotation())
# N: Revealed type is "__main__.My"

Link: https://mypy-play.net/?mypy=latest&python=3.12&gist=58161f0ca82a956a0f893c4f86a90786

And since I am using a Container subclass to specialize dep injection a bit - it does matter to me.

sobolevn avatar Jun 29 '24 10:06 sobolevn