Skip to content

Commit

Permalink
refactor utils.deprecated to be more mypy friendly
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Mar 2, 2022
1 parent 1cc4a6e commit 5b81e64
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
7 changes: 4 additions & 3 deletions src/cryptography/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,15 +139,16 @@ def __dir__(self) -> typing.Sequence[str]:


def deprecated(
name: str,
value: object,
module_name: str,
message: str,
warning_class: typing.Type[Warning],
) -> _DeprecatedValue:
):
module = sys.modules[module_name]
if not isinstance(module, _ModuleWithDeprecations):
sys.modules[module_name] = _ModuleWithDeprecations(module)
return _DeprecatedValue(value, message, warning_class)
sys.modules[module_name] = module = _ModuleWithDeprecations(module)
setattr(module, name, _DeprecatedValue(value, message, warning_class))


def cached_property(func: typing.Callable) -> property:
Expand Down
9 changes: 7 additions & 2 deletions tests/deprecated_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@

# This module exists to test `cryptography.utils.deprecated`

DEPRECATED = utils.deprecated(
3, __name__, "Test Deprecated Object", DeprecationWarning
DEPRECATED = 3
utils.deprecated(
"DEPRECATED",
DEPRECATED,
__name__,
"Test Deprecated Object",
DeprecationWarning,
)

NOT_DEPRECATED = 12
12 changes: 8 additions & 4 deletions tests/test_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ class TestDeprecated:
def test_deprecated(self, monkeypatch):
mod = types.ModuleType("TestDeprecated/test_deprecated")
monkeypatch.setitem(sys.modules, mod.__name__, mod)
mod.X = deprecated(
deprecated(
name="X",
value=1,
module_name=mod.__name__,
message="deprecated message text",
warning_class=DeprecationWarning,
)
mod.Y = deprecated(
deprecated(
name="Y",
value=2,
module_name=mod.__name__,
message="more deprecated text",
Expand Down Expand Up @@ -53,13 +55,15 @@ def test_deprecated(self, monkeypatch):
def test_deleting_deprecated_members(self, monkeypatch):
mod = types.ModuleType("TestDeprecated/test_deprecated")
monkeypatch.setitem(sys.modules, mod.__name__, mod)
mod.X = deprecated(
deprecated(
name="X",
value=1,
module_name=mod.__name__,
message="deprecated message text",
warning_class=DeprecationWarning,
)
mod.Y = deprecated(
deprecated(
name="Y",
value=2,
module_name=mod.__name__,
message="more deprecated text",
Expand Down

0 comments on commit 5b81e64

Please sign in to comment.