Skip to content

Commit c42ae53

Browse files
authored
update to latest pyright (posit-dev/positron-python#278)
* update to pyright 1.1.339 * a lot of the function signatures we are vendoring in change between Python versions, so we will end up with CI errors on various Python versions unless we ignore the `reportIncompatibleMethodOverride` errors. if this becomes an ongoing issue, let's move this ignore to a project level.
1 parent d724e6c commit c42ae53

File tree

8 files changed

+37
-46
lines changed

8 files changed

+37
-46
lines changed

extensions/positron-python/pythonFiles/positron/inspectors.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,9 @@
1313
import types
1414
import uuid
1515
from abc import ABC, abstractmethod
16-
from collections.abc import (
17-
Mapping,
18-
MutableMapping,
19-
MutableSequence,
20-
MutableSet,
21-
Sequence,
22-
Set,
23-
)
16+
from collections.abc import Mapping, MutableMapping, MutableSequence, MutableSet, Sequence, Set
2417
from typing import (
18+
TYPE_CHECKING,
2519
Any,
2620
Callable,
2721
Collection,
@@ -35,7 +29,6 @@
3529
Protocol,
3630
Sized,
3731
Tuple,
38-
TYPE_CHECKING,
3932
Type,
4033
TypeVar,
4134
Union,
@@ -567,7 +560,7 @@ def copy(self, value: torch.Tensor) -> torch.Tensor:
567560

568561

569562
class _BaseMapInspector(PositronInspector[MT], ABC):
570-
def get_kind(self, value: Mapping) -> str:
563+
def get_kind(self, value: MT) -> str:
571564
return "map"
572565

573566
@abstractmethod

extensions/positron-python/pythonFiles/positron/positron_ipkernel.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,32 @@
44

55
""" Positron extensions to the iPython Kernel."""
66
from __future__ import annotations
7+
78
import asyncio
89
import logging
910
import warnings
1011
from collections.abc import Iterable
1112
from itertools import chain
12-
from typing import Any, Callable, Container, Dict, Mapping, Optional, Set, Tuple, Type
13+
from typing import Any, Callable, Container, Coroutine, Dict, Mapping, Optional, Set, Tuple, Type
1314

15+
import traitlets
1416
from ipykernel.comm.manager import CommManager
1517
from ipykernel.ipkernel import IPythonKernel
1618
from ipykernel.kernelapp import IPKernelApp
17-
from ipykernel.zmqshell import ZMQInteractiveShell, ZMQDisplayPublisher
18-
from IPython.core import oinspect
19+
from ipykernel.zmqshell import ZMQDisplayPublisher, ZMQInteractiveShell
20+
from IPython.core import oinspect, page
1921
from IPython.core.interactiveshell import InteractiveShell
20-
from IPython.core.magic import Magics, line_magic, magics_class, needs_local_scope, MagicsManager
21-
from IPython.core import page
22+
from IPython.core.magic import Magics, MagicsManager, line_magic, magics_class, needs_local_scope
2223
from IPython.utils import PyColorize
23-
import traitlets
2424

2525
from .dataviewer import DataViewerService
26-
from .variables import VariablesService
2726
from .frontend import FrontendService
2827
from .help import HelpService
2928
from .inspectors import get_inspector
3029
from .lsp import LSPService
3130
from .plots import PositronDisplayPublisherHook
3231
from .utils import cancel_tasks, create_task
32+
from .variables import VariablesService
3333

3434
POSITRON_DATA_VIEWER_COMM = "positron.dataViewer"
3535
"""The comm channel target_name for Positron's Data Viewer"""
@@ -69,12 +69,11 @@ class PositronIPythonInspector(oinspect.Inspector):
6969
def pinfo(
7070
self,
7171
obj: Any,
72-
oname: str,
73-
formatter: Callable[[str], Dict[str, str]],
74-
info: oinspect.OInfo,
75-
*,
76-
detail_level: int,
77-
enable_html_pager: bool,
72+
oname: str = "",
73+
formatter: Optional[Callable[[str], Dict[str, str]]] = None,
74+
info: Optional[oinspect.OInfo] = None,
75+
detail_level: int = 0,
76+
enable_html_pager: bool = True,
7877
omit_sections: Container[str] = (),
7978
) -> None:
8079
# Intercept `%pinfo obj` / `obj?` calls, and instead use Positron's help service
@@ -106,7 +105,7 @@ class PositronShell(ZMQInteractiveShell):
106105
).tag(config=True)
107106

108107
@traitlets.observe("colors")
109-
def init_inspector(self, change: Optional[traitlets.Bunch] = None) -> None:
108+
def init_inspector(self, changes: Optional[traitlets.Bunch] = None) -> None:
110109
# Override to pass `parent=self` to the inspector
111110
self.inspector = self.inspector_class(
112111
oinspect.InspectColors,
@@ -160,7 +159,6 @@ class PositronIPyKernel(IPythonKernel):
160159

161160
shell: PositronShell
162161
comm_manager: CommManager
163-
execution_count: int
164162

165163
shell_class: PositronShell = traitlets.Type(PositronShell, klass=InteractiveShell) # type: ignore
166164

@@ -230,7 +228,7 @@ def start(self) -> None:
230228
super().start()
231229
self.help_service.start()
232230

233-
async def do_shutdown(self, restart: bool) -> Dict[str, Any]:
231+
async def do_shutdown(self, restart: bool) -> Dict[str, str | bool]: # type: ignore ReportIncompatibleMethodOverride
234232
"""
235233
Handle kernel shutdown.
236234
"""

extensions/positron-python/pythonFiles/positron/positron_jedilsp.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ class HelpTopicRequest:
122122

123123

124124
class PositronJediLanguageServerProtocol(JediLanguageServerProtocol):
125-
def get_message_type(self, method: str) -> Optional[Type]:
125+
def get_message_type(self, method: str) -> Optional[Type]: # type: ignore
126126
# Overriden to include custom Positron LSP messages.
127127
# Doing so ensures that the corresponding feature function receives `params` of the correct type.
128128
if method == _HELP_TOPIC:
@@ -137,7 +137,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
137137
super().__init__(*args, **kwargs)
138138

139139
self.loop: asyncio.AbstractEventLoop
140-
self.lsp: PositronJediLanguageServerProtocol
140+
self.lsp: PositronJediLanguageServerProtocol # type: ignore reportIncompatibleVariableOverride
141141

142142
# LSP comm used to notify the frontend when the server is ready
143143
self._comm: Optional[BaseComm] = None
@@ -363,7 +363,7 @@ def positron_completion(
363363
has_whitespace = " " in trimmed_line
364364
if server.kernel is not None and not (is_completing_attribute or has_whitespace):
365365
# Cast type from traitlets.Dict to typing.Dict
366-
magic_commands = cast(Dict[str, Callable], server.kernel.shell.magics_manager.lsmagic())
366+
magic_commands = cast(Dict[str, Any], server.kernel.shell.magics_manager.lsmagic())
367367

368368
chars_before_cursor = trimmed_line[: params.position.character]
369369

extensions/positron-python/pythonFiles/positron/pydoc.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def page(self, title, contents):
218218
)
219219
# --- End Positron ---
220220

221-
def heading(self, title: str, extras="") -> str:
221+
def heading(self, title: str, extras="") -> str: # type: ignore ReportIncompatibleMethodOverride
222222
"""Format a page heading."""
223223
# Simplified version of pydoc.HTMLDoc.heading that doesn't use tables
224224
lines = [f"<h1>{title}</h1>"]
@@ -227,7 +227,7 @@ def heading(self, title: str, extras="") -> str:
227227
result = "\n".join(lines)
228228
return result
229229

230-
def section(
230+
def section( # type: ignore
231231
self,
232232
title: str,
233233
cls: str,
@@ -236,7 +236,7 @@ def section(
236236
prelude="",
237237
marginalia=None,
238238
gap=None,
239-
) -> str:
239+
) -> str: # type: ignore ReportIncompatibleMethodOverride
240240
"""Format a section with a heading."""
241241
# Simplified version of pydoc.HTMLDoc.section that doesn't use tables
242242
if width is not None:
@@ -264,7 +264,7 @@ def bigsection(self, *args):
264264
return self.section(*args)
265265

266266
# Heavily customized version of pydoc.HTMLDoc.docmodule
267-
def docmodule(self, object: ModuleType, *_):
267+
def docmodule(self, object: ModuleType, *_): # type: ignore reportIncompatibleMethodOverride
268268
obj_name = object.__name__
269269

270270
# Create the heading, with links to each parent module
@@ -338,7 +338,7 @@ def docmodule(self, object: ModuleType, *_):
338338
return result
339339

340340
# Heavily customized version of pydoc.HTMLDoc.docclass
341-
def docclass(self, obj: Type, name=None, *_):
341+
def docclass(self, obj: Type, name=None, *_): # type: ignore reportIncompatibleMethodOverride
342342
obj_name = name or obj.__name__
343343

344344
# Separate the class's members into attributes and methods
@@ -497,7 +497,7 @@ def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
497497
return text
498498

499499
# as is from pydoc.HTMLDoc to port Python 3.11 breaking CSS changes
500-
def index(self, dir, shadowed: Optional[Dict[str, int]] = None):
500+
def index(self, dir, shadowed: Optional[Dict[str, int]] = None): # type: ignore reportIncompatibleMethodOverride
501501
"""Generate an HTML index for a directory of modules."""
502502
modpkgs = []
503503
if shadowed is None:

extensions/positron-python/pythonFiles/tests/positron/conftest.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import pytest
55
from IPython.conftest import get_ipython
66
from IPython.terminal.interactiveshell import TerminalInteractiveShell
7-
87
from positron.positron_ipkernel import PositronIPyKernel
98

109

@@ -17,7 +16,7 @@ def __init__(self, *args, **kwargs):
1716
self.messages = []
1817
super().__init__(*args, **kwargs)
1918

20-
def publish_msg(self, msg_type, **msg):
19+
def publish_msg(self, msg_type, **msg): # type: ignore ReportIncompatibleMethodOverride
2120
msg["msg_type"] = msg_type
2221
self.messages.append(msg)
2322

extensions/positron-python/pythonFiles/tests/positron/test_plots.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
import codecs
22
import pickle
33
from pathlib import Path
4-
from typing import cast, Iterable
4+
from typing import Iterable, cast
55

66
import matplotlib
77
import matplotlib.pyplot as plt
88
import pytest
99
from IPython.conftest import get_ipython
1010
from IPython.core.formatters import DisplayFormatter
11+
from matplotlib.axes import Axes
1112
from matplotlib.figure import Figure
1213
from matplotlib.testing.compare import compare_images
1314
from matplotlib_inline.backend_inline import configure_inline_support
14-
1515
from positron.plots import BASE_DPI, PositronDisplayPublisherHook
1616

1717
from .conftest import DummyComm
1818

19-
2019
PLOT_DATA = [1, 2]
2120

2221

@@ -113,8 +112,9 @@ def test_hook_call(hook: PositronDisplayPublisherHook, images_path: Path) -> Non
113112
fig.savefig(str(actual))
114113

115114
# Create the reference figure
116-
fig_ref: plt.figure.Figure = plt.figure()
117-
fig_ref.subplots().plot(PLOT_DATA)
115+
fig_ref = cast(Figure, plt.figure())
116+
fig_axes = cast(Axes, fig_ref.subplots())
117+
fig_axes.plot(PLOT_DATA)
118118
expected = images_path / "test-hook-call-expected.png"
119119
fig_ref.savefig(str(expected))
120120

@@ -210,8 +210,9 @@ def test_hook_render(figure_comm: DummyComm, images_path: Path) -> None:
210210
width_in = width_px / BASE_DPI
211211
height_in = height_px / BASE_DPI
212212

213-
fig_ref: plt.figure.Figure = plt.figure()
214-
fig_ref.subplots().plot([1, 2])
213+
fig_ref = cast(Figure, plt.figure())
214+
fig_axes = cast(Axes, fig_ref.subplots())
215+
fig_axes.plot([1, 2])
215216
fig_ref.set_dpi(dpi)
216217
fig_ref.set_size_inches(width_in, height_in)
217218

extensions/positron-python/pythonFiles/tests/test_create_venv.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def redirect_io(stream: str, new_stream):
242242
class CustomIO(io.TextIOWrapper):
243243
"""Custom stream object to replace stdio."""
244244

245-
name: str = "customio"
245+
name: str = "customio" # type: ignore ReportIncompatibleMethodOverride (remove once updated upstream)
246246

247247
def __init__(self, name: str, encoding="utf-8", newline=None):
248248
self._buffer = io.BytesIO()

extensions/positron-python/pythonFiles/vscode_pytest/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ def post_response(cwd: str, session_node: TestNode) -> None:
689689
class PathEncoder(json.JSONEncoder):
690690
"""A custom JSON encoder that encodes pathlib.Path objects as strings."""
691691

692-
def default(self, obj):
692+
def default(self, obj): # type: ignore ReportIncompatibleMethodOverride (remove once updated upstream)
693693
if isinstance(obj, pathlib.Path):
694694
return os.fspath(obj)
695695
return super().default(obj)

0 commit comments

Comments
 (0)