Add getattr overload variants to help mypy type inference (#6355)

These silence errors about missing type annotations for calls
like these:

```
x = getattr(o, 'a', [])
y = getattr(o, 'b', {})
```

This is basically a generalization of #5518 and other overloads we already
have.

This works around python/mypy#11572. I encountered the issue in several
places when testing recent typeshed against an internal repo.
This commit is contained in:
Jukka Lehtosalo
2021-11-22 11:08:40 +00:00
committed by GitHub
parent 848753a4a9
commit 25649bc1e5
3 changed files with 21 additions and 6 deletions

View File

@@ -850,13 +850,18 @@ def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicod
@overload
def getattr(__o: Any, name: Text) -> Any: ...
# While technically covered by the last overload, spelling out the types for None and bool
# help mypy out in some tricky situations involving type context (aka bidirectional inference)
# While technically covered by the last overload, spelling out the types for None, bool
# and basic containers help mypy out in some tricky situations involving type context
# (aka bidirectional inference)
@overload
def getattr(__o: Any, name: Text, __default: None) -> Any | None: ...
@overload
def getattr(__o: Any, name: Text, __default: bool) -> Any | bool: ...
@overload
def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ...
@overload
def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ...
@overload
def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ...
def globals() -> Dict[str, Any]: ...
def hasattr(__obj: Any, __name: Text) -> bool: ...

View File

@@ -850,13 +850,18 @@ def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicod
@overload
def getattr(__o: Any, name: Text) -> Any: ...
# While technically covered by the last overload, spelling out the types for None and bool
# help mypy out in some tricky situations involving type context (aka bidirectional inference)
# While technically covered by the last overload, spelling out the types for None, bool
# and basic containers help mypy out in some tricky situations involving type context
# (aka bidirectional inference)
@overload
def getattr(__o: Any, name: Text, __default: None) -> Any | None: ...
@overload
def getattr(__o: Any, name: Text, __default: bool) -> Any | bool: ...
@overload
def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ...
@overload
def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ...
@overload
def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ...
def globals() -> Dict[str, Any]: ...
def hasattr(__obj: Any, __name: Text) -> bool: ...