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 57f45de
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
9 changes: 7 additions & 2 deletions src/cryptography/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,16 @@ def deprecated(
module_name: str,
message: str,
warning_class: typing.Type[Warning],
name: typing.Optional[str] = None,
) -> _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)
dv = _DeprecatedValue(value, message, warning_class)
# Maintain backwards compatibility with `name is None` for pyOpenSSL.
if name is not None:
setattr(module, name, dv)
return dv


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,
__name__,
"Test Deprecated Object",
DeprecationWarning,
name="DEPRECATED",
)

NOT_DEPRECATED = 12
6 changes: 4 additions & 2 deletions tests/test_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ 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",
Expand Down Expand Up @@ -53,7 +54,8 @@ 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",
Expand Down

0 comments on commit 57f45de

Please sign in to comment.