Skip to content

Commit

Permalink
Use get_typing_hints instead of __annotations__ to resolve types in P…
Browse files Browse the repository at this point in the history
…ython 3.10 (#297)

Summary:
**What:**

Fixes #296

**Why:**

Due to PEP 563 becoming default in Python 3.10 the `__annotations__` value doesn't store types and it stores string values. Using `typing.get_type_hints` ensures the types are evaluated and returned like behavior before Python 3.10 .

**How:**

**Risks:**

**Checklist**:

<!--
Have you done all of these things?
To check an item, place an "x" in the box like so: "- [x] Tests"
Add "N/A" to the end of each line that's irrelevant to your changes
-->

- [ ] Added tests, if you've added code that should be tested
- [ ] Updated the documentation, if you've changed APIs
- [ ] Ensured the test suite passes
- [ ] Made sure your code lints
- [ ] Completed the Contributor License Agreement ("CLA")

Pull Request resolved: #297

Reviewed By: lsiudut

Differential Revision: D27645783

Pulled By: deathowl

fbshipit-source-id: eb1d41abcccad9e5d6cc92554472e0d083bebf4f
  • Loading branch information
tirkarthi authored and facebook-github-bot committed Apr 15, 2021
1 parent f42e0e9 commit 4499047
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions testslide/strict_mock.py
Expand Up @@ -7,7 +7,17 @@
import inspect
import os.path
from types import FrameType
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
get_type_hints,
)

import testslide.lib
import testslide.mock_callable
Expand Down Expand Up @@ -623,8 +633,12 @@ def __validate_attribute_type(self, name: str, value: Any) -> None:
):
return

if hasattr(self._template, "__annotations__"):
annotations = self._template.__annotations__
if self._template is not None:
try:
annotations = get_type_hints(self._template)
except Exception:
# Some modules can throw KeyError : https://bugs.python.org/issue41515
annotations = {}
if name in annotations:
testslide.lib._validate_argument_type(annotations[name], name, value)

Expand Down

0 comments on commit 4499047

Please sign in to comment.