Skip to content

BUG: ScopingPolicy members improperly typed #426

@TTsangSC

Description

@TTsangSC

Description

Somehow mypy isn't recognizing that the ScopingPolicy members are its own instances and are hence strings; maybe it has to do with the hacky backport we have for enum.StrEnum (line_profiler.line_profiler_utils._StrEnumBase).

Example script (scoping-policy-type-bug.py)

from line_profiler.line_profiler import LineProfiler
from line_profiler.scoping_policy import ScopingPolicy


class MyClass:
    pass


def main() -> None:
    prof = LineProfiler()
    prof.add_class(MyClass, scoping_policy=ScopingPolicy.NONE)

Output

$ mypy scoping-policy-enum-bug.py
scoping-policy-type-bug.py:11 error: argument "scoping_policy" to "add_class" of "LineProfiler" has incompatible type "auto"; expected "ScopingPolicy | str | ScopingPolicyDict | None"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Mitigation

I noticed that in #419 we're circumventing this within the codebase with manual type-casting (cast(ScopingPolicy, ScopingPolicy.<attr>); see d1b4c23). In some sense this is alright, since end users are more likely to just use the string forms for LineProfiler.add_*(..., scoping_policy=<policy>)... but we should probably fix this more thoroughly since ScopingPolicy is public API, and having the imported enum class not work would be quite counterintuitive.

Wonder if something like

class _StrEnumBase(str, enum.Enum):
    ...


if TYPE_CHECKING:
    from enum import StrEnum as _StrEnumBase  # type: ignore[attr-defined]


class StringEnum(_StrEnumBase):
    ...

in line_profiler/line_profiler_utils.py would work... if not, we may have to use the enum.auto-subclassing workaround.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions