From 242fc57dec09a59994f5d7541d46a533fac7a34d Mon Sep 17 00:00:00 2001 From: "Terence S.-C. Tsang" Date: Fri, 13 Mar 2026 07:54:08 +0100 Subject: [PATCH] Implementing fix suggested in #426 CHANGELOG.rst Added entry line_profiler/line_profiler.py::LineProfiler._add_namespace(...) Removed unnecessary `typing.cast()` in default arguments line_profiler/line_profiler_utils.py _StrEnum New alias which resolves: - Statically, always to `enum.StrEnum` - At the runtime, also thereto if available, and to `_StrEnumBase` otherwise StringEnum Now always "statically" inheriting from `_StrEnum` to make things less confusing to the type-checker --- CHANGELOG.rst | 2 ++ line_profiler/line_profiler.py | 12 +++--------- line_profiler/line_profiler_utils.py | 9 ++++++++- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index d28eb7cf..8780a80d 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,6 +6,8 @@ Changes * FIX: Make sure that the profiled code is run in the ``sys.modules['__main__']`` namespace to avoid issues w/e.g. pickling (#423) +* FIX: ``ScopingPolicy`` members now type-check properly as instances thereof + (#427) 5.0.2 diff --git a/line_profiler/line_profiler.py b/line_profiler/line_profiler.py index ceb595b8..bede6f6c 100755 --- a/line_profiler/line_profiler.py +++ b/line_profiler/line_profiler.py @@ -600,15 +600,9 @@ def _add_namespace( namespace: type | types.ModuleType, *, seen: set[int] | None = None, - func_scoping_policy: ScopingPolicy = cast( - ScopingPolicy, ScopingPolicy.NONE - ), - class_scoping_policy: ScopingPolicy = cast( - ScopingPolicy, ScopingPolicy.NONE - ), - module_scoping_policy: ScopingPolicy = cast( - ScopingPolicy, ScopingPolicy.NONE - ), + func_scoping_policy: ScopingPolicy = ScopingPolicy.NONE, + class_scoping_policy: ScopingPolicy = ScopingPolicy.NONE, + module_scoping_policy: ScopingPolicy = ScopingPolicy.NONE, wrap: bool = False, name: str | None = None, ) -> int: diff --git a/line_profiler/line_profiler_utils.py b/line_profiler/line_profiler_utils.py index b42bb647..887cdd55 100644 --- a/line_profiler/line_profiler_utils.py +++ b/line_profiler/line_profiler_utils.py @@ -46,7 +46,14 @@ def __str__(self) -> str: return self.value -class StringEnum(getattr(enum, 'StrEnum', _StrEnumBase)): # type: ignore[misc] +try: + from enum import StrEnum as _StrEnum +except ImportError: + if not typing.TYPE_CHECKING: # Don't confuse the typechecker + _StrEnum = _StrEnumBase + + +class StringEnum(_StrEnum): """ Convenience wrapper around :py:class:`enum.StrEnum`.