python / typeshed

Collection of library stubs for Python, with static types
Other
4.31k stars 1.73k forks source link

Should `traceback.FrameSummary` have a "slice" overload? #12478

Open mwichmann opened 1 month ago

mwichmann commented 1 month ago

The (relatively new - 3.5+) FrameSummary object does support slicing in a limited way like old frames did, as it indexes into a tuple, but the typeshed stubs don't have an @overload for that, so checkers complain. The current implementation in FrameSummary is:

    def __getitem__(self, pos):
        return (self.filename, self.lineno, self.name, self.line)[pos]

So this small snip, from old code that well precedes Python 3.5, continues to work:

    for caller in tb[2:]:
        caller = callee + caller[:3]

but mypy grumps with:

error: No overload variant of "__getitem__" of "FrameSummary" matches argument type "slice"  [call-overload]

I'm not entirely sold that this is something that should be added, so I've couched this as a question... (getting grumps from my project, of course).

Daverball commented 1 month ago

Seems like a reasonable addition to me. Typeshed generally aims to model the runtime behavior as well as possible. Here it seems like you could just change the final overload to def __getitem__(self, pos: int | slice) -> Any: ..., the only reason to add an additional overload for slice would be to get the slightly more accurate return type tuple[Any, ...].

Feel free to open a pull request. If you need it in your own code and the addition doesn't negatively impact other users, it will generally be accepted.