From 44990479e035a05fc265e7e88c8a14f5c01590d2 Mon Sep 17 00:00:00 2001 From: Karthikeyan Singaravelan Date: Thu, 15 Apr 2021 07:28:50 -0700 Subject: [PATCH] Use get_typing_hints instead of __annotations__ to resolve types in Python 3.10 (#297) Summary: **What:** Fixes https://github.com/facebook/TestSlide/issues/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**: - [ ] 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: https://github.com/facebook/TestSlide/pull/297 Reviewed By: lsiudut Differential Revision: D27645783 Pulled By: deathowl fbshipit-source-id: eb1d41abcccad9e5d6cc92554472e0d083bebf4f --- testslide/strict_mock.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/testslide/strict_mock.py b/testslide/strict_mock.py index cfa719c..67ad779 100644 --- a/testslide/strict_mock.py +++ b/testslide/strict_mock.py @@ -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 @@ -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)