Skip to content

Commit

Permalink
Upgrade type definitions and apply pyupgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
philippjfr committed Nov 16, 2024
1 parent 396ad6d commit 71912de
Show file tree
Hide file tree
Showing 67 changed files with 288 additions and 297 deletions.
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
default_stages: [pre-commit]
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.19.0
hooks:
- id: pyupgrade
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
Expand Down
8 changes: 4 additions & 4 deletions doc/generate_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def write_file(name, text, opts):
"""Write the output file for module/package <name>."""
if opts.dryrun:
return
fname = os.path.join(opts.destdir, "%s.%s" % (name, opts.suffix))
fname = os.path.join(opts.destdir, "{}.{}".format(name, opts.suffix))
if not opts.force and os.path.isfile(fname):
print('File %s already exists, skipping.' % fname)
else:
Expand All @@ -69,7 +69,7 @@ def write_file(name, text, opts):
def format_heading(level, text):
"""Create a heading of <level> [1, 2 or 3 supported]."""
underlining = ['=', '-', '~', ][level-1] * len(text)
return '%s\n%s\n\n' % (text, underlining)
return '{}\n{}\n\n'.format(text, underlining)

def format_directive(module, package=None):
"""Create the automodule directive and add the options."""
Expand All @@ -89,7 +89,7 @@ def create_module_file(package, module, opts):
def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
package = os.path.split(root)[-1]
text = format_heading(1, '%s.%s Package' % (master_package, package))
text = format_heading(1, '{}.{} Package'.format(master_package, package))
text += '\n---------\n\n'
# add each package's module
for py_file in py_files:
Expand All @@ -114,7 +114,7 @@ def create_package_file(root, master_package, subroot, py_files, opts, subs):
text += format_heading(2, 'Subpackages')
text += '.. toctree::\n\n'
for sub in subs:
text += ' %s.%s\n' % (makename(master_package, subroot), sub)
text += ' {}.{}\n'.format(makename(master_package, subroot), sub)
text += '\n'

write_file(makename(master_package, subroot), text, opts)
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/django/sliders/sinewave.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class SineWave(param.Parameterized):
y_range = param.Range(default=(-2.5,2.5),bounds=(-10,10))

def __init__(self, **params):
super(SineWave, self).__init__(**params)
super().__init__(**params)
x, y = self.sine()
self.cds = ColumnDataSource(data=dict(x=x, y=y))
self.plot = figure(height=400, width=400,
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/django_multi_apps/gbm/pn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class GBM(param.Parameterized):
refresh = pn.widgets.Button(name="Refresh", button_type='primary')

def __init__(self, **params):
super(GBM, self).__init__(**params)
super().__init__(**params)

# update the plot for every changes
# @param.depends('mean', 'volatility', 'maturity', 'n_observations', 'n_simulations', watch=True)
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/django_multi_apps/sliders/pn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class SineWave(param.Parameterized):
y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10))

def __init__(self, **params):
super(SineWave, self).__init__(**params)
super().__init__(**params)
x, y = self.sine()
self.cds = ColumnDataSource(data=dict(x=x, y=y))
self.plot = figure(height=400, width=400,
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/django_multi_apps/stockscreener/pn_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class StockScreener(param.Parameterized):
def __init__(self, df, **params):
start = dt.date(year=df.index[0].year, month=df.index[0].month, day=df.index[0].day)
end = dt.date(year=df.index[-1].year, month=df.index[-1].month, day=df.index[-1].day)
super(StockScreener, self).__init__(df=df, start=start, **params)
super().__init__(df=df, start=start, **params)
self.param.start.bounds = (start, end)
columns = list(self.df.columns)
self.param.index.objects = columns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class StockScreener(param.Parameterized):
From = pn.widgets.DateSlider()

def __init__(self, df, **params):
super(StockScreener, self).__init__(**params)
super().__init__(**params)
# init df
self.df = df
self.start_date = dt.datetime(year=df.index[0].year, month=df.index[0].month, day=df.index[0].day)
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/fastApi/sliders/sinewave.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class SineWave(param.Parameterized):
y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10))

def __init__(self, **params):
super(SineWave, self).__init__(**params)
super().__init__(**params)
x, y = self.sine()
self.cds = ColumnDataSource(data=dict(x=x, y=y))
self.plot = figure(height=400, width=400,
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/fastApi_multi_apps/sliders/sinewave.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class SineWave(param.Parameterized):
y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10))

def __init__(self, **params):
super(SineWave, self).__init__(**params)
super().__init__(**params)
x, y = self.sine()
self.cds = ColumnDataSource(data=dict(x=x, y=y))
self.plot = figure(height=400, width=400,
Expand Down
2 changes: 1 addition & 1 deletion examples/apps/fastApi_multi_apps/sliders2/sinewave.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class SineWave(param.Parameterized):
y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10))

def __init__(self, **params):
super(SineWave, self).__init__(**params)
super().__init__(**params)
x, y = self.sine()
self.cds = ColumnDataSource(data=dict(x=x, y=y))
self.plot = figure(height=400, width=400,
Expand Down
8 changes: 4 additions & 4 deletions panel/chat/input.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from typing import (
TYPE_CHECKING, Any, ClassVar, Mapping, Optional,
TYPE_CHECKING, Any, ClassVar, Mapping,
)

import param
Expand Down Expand Up @@ -87,9 +87,9 @@ def _get_properties(self, doc: Document) -> dict[str, Any]:
def _get_model(
self,
doc: Document,
root: Optional[Model] = None,
parent: Optional[Model] = None,
comm: Optional[Comm] = None,
root: Model | None = None,
parent: Model | None = None,
comm: Comm | None = None,
) -> Model:
model = super()._get_model(doc, root, parent, comm)
self._register_events("chat_message_event", model=model, doc=doc, comm=comm)
Expand Down
10 changes: 5 additions & 5 deletions panel/chat/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ def wrapper(self, event: param.parameterized.Event):
def _click_send(
self,
event: param.parameterized.Event | None = None,
instance: "ChatInterface" | None = None
instance: ChatInterface | None = None
) -> None:
"""
Send the input when the user presses Enter.
Expand Down Expand Up @@ -430,7 +430,7 @@ def _click_send(
def _click_stop(
self,
event: param.parameterized.Event | None = None,
instance: "ChatInterface" | None = None
instance: ChatInterface | None = None
) -> bool:
"""
Cancel the callback when the user presses the Stop button.
Expand Down Expand Up @@ -479,7 +479,7 @@ def _reset_button_data(self):
def _click_rerun(
self,
event: param.parameterized.Event | None = None,
instance: "ChatInterface" | None = None
instance: ChatInterface | None = None
) -> None:
"""
Upon clicking the rerun button, rerun the last user message,
Expand All @@ -494,7 +494,7 @@ def _click_rerun(
def _click_undo(
self,
event: param.parameterized.Event | None = None,
instance: "ChatInterface" | None = None
instance: ChatInterface | None = None
) -> None:
"""
Upon clicking the undo button, undo (remove) messages
Expand All @@ -518,7 +518,7 @@ def _click_undo(
def _click_clear(
self,
event: param.parameterized.Event | None = None,
instance: "ChatInterface" | None = None
instance: ChatInterface | None = None
) -> None:
"""
Upon clicking the clear button, clear the chat log.
Expand Down
8 changes: 4 additions & 4 deletions panel/chat/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from typing import Any, Union
from typing import Any

try:
from langchain.callbacks.base import BaseCallbackHandler
Expand Down Expand Up @@ -108,7 +108,7 @@ def on_llm_end(self, response: LLMResult, *args, **kwargs):
self._reset_active()
return super().on_llm_end(response, *args, **kwargs)

def on_llm_error(self, error: Union[Exception, KeyboardInterrupt], *args, **kwargs):
def on_llm_error(self, error: Exception | KeyboardInterrupt, *args, **kwargs):
return super().on_llm_error(error, *args, **kwargs)

def on_agent_action(self, action: AgentAction, *args, **kwargs: Any) -> Any:
Expand All @@ -130,7 +130,7 @@ def on_tool_end(self, output: str, *args, **kwargs):
return super().on_tool_end(output, *args, **kwargs)

def on_tool_error(
self, error: Union[Exception, KeyboardInterrupt], *args, **kwargs
self, error: Exception | KeyboardInterrupt, *args, **kwargs
):
return super().on_tool_error(error, *args, **kwargs)

Expand All @@ -146,7 +146,7 @@ def on_chain_end(self, outputs: dict[str, Any], *args, **kwargs):
return super().on_chain_end(outputs, *args, **kwargs)

def on_retriever_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
self, error: Exception | KeyboardInterrupt, **kwargs: Any
) -> Any:
"""Run when Retriever errors."""
return super().on_retriever_error(error, **kwargs)
Expand Down
4 changes: 2 additions & 2 deletions panel/chat/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from io import BytesIO
from tempfile import NamedTemporaryFile
from typing import (
TYPE_CHECKING, Any, Callable, ClassVar, Optional, Union,
TYPE_CHECKING, Any, Callable, ClassVar, Union,
)
from zoneinfo import ZoneInfo

Expand Down Expand Up @@ -667,7 +667,7 @@ def update(
self.param.update(**updates)

def select(
self, selector: Optional[type | Callable[[Viewable], bool]] = None
self, selector: type | Callable[[Viewable], bool] | None = None
) -> list[Viewable]:
return super().select(selector) + self._composite.select(selector)

Expand Down
16 changes: 8 additions & 8 deletions panel/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from collections import defaultdict
from functools import partial
from typing import (
TYPE_CHECKING, Any, Callable, ClassVar, Literal, Mapping, Optional,
TYPE_CHECKING, Any, Callable, ClassVar, Literal, Mapping,
)

import param
Expand Down Expand Up @@ -141,9 +141,9 @@ def _create__view(self):
return view

def _get_model(
self, doc: Document, root: Optional['Model'] = None,
parent: Optional['Model'] = None, comm: Optional[Comm] = None
) -> 'Model':
self, doc: Document, root: Model | None = None,
parent: Model | None = None, comm: Comm | None = None
) -> Model:
if self._view__ is None:
self._view__ = self._create__view()
model = self._view__._get_model(doc, root, parent, comm)
Expand Down Expand Up @@ -472,8 +472,8 @@ def _setup_autoreload(self):
state.execute(self._watch_esm)

def _get_model(
self, doc: Document, root: Optional[Model] = None,
parent: Optional[Model] = None, comm: Optional[Comm] = None
self, doc: Document, root: Model | None = None,
parent: Model | None = None, comm: Comm | None = None
) -> Model:
model = self._bokeh_model(**self._get_properties(doc))
root = root or model
Expand All @@ -486,7 +486,7 @@ def _get_model(
self._setup_autoreload()
return model

def _process_event(self, event: 'Event') -> None:
def _process_event(self, event: Event) -> None:
if isinstance(event, DataEvent):
for cb in self._msg__callbacks:
state.execute(partial(cb, event), schedule=False)
Expand All @@ -501,7 +501,7 @@ def _process_event(self, event: 'Event') -> None:

def _update_model(
self, events: dict[str, param.parameterized.Event], msg: dict[str, Any],
root: Model, model: Model, doc: Document, comm: Optional[Comm]
root: Model, model: Model, doc: Document, comm: Comm | None
) -> None:
model_msg, data_msg = {}, {}
for prop, v in list(msg.items()):
Expand Down
2 changes: 1 addition & 1 deletion panel/io/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def _get_model(
def get_root(
self, doc: Document | None = None, comm: Comm | None = None,
preprocess: bool = True
) -> 'Model':
) -> Model:
doc = create_doc_if_none_exists(doc)
root = self._get_model(doc, comm=comm)
ref = root.ref['id']
Expand Down
2 changes: 1 addition & 1 deletion panel/io/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def _io_hash(obj):
functools.partial : _partial_hash,
unittest.mock.Mock : lambda obj: _int_to_bytes(id(obj)),
(io.StringIO, io.BytesIO): _io_hash,
dt.date : lambda obj: f'{type(obj).__name__}{obj}'.encode('utf-8'),
dt.date : lambda obj: f'{type(obj).__name__}{obj}'.encode(),
# Fully qualified type strings
'numpy.ndarray' : _numpy_hash,
'pandas.core.series.Series' : _pandas_hash,
Expand Down
2 changes: 1 addition & 1 deletion panel/io/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def find_components(module_or_file: str | os.PathLike, classes: list[str] | None
if py_file:
v.__path__ = path_obj.parent.absolute()
components.append(v)
not_found = {cls for cls in classes if '*' not in cls} - set(c.__name__ for c in components)
not_found = {cls for cls in classes if '*' not in cls} - {c.__name__ for c in components}
if classes and not_found:
clss = ', '.join(map(repr, not_found))
raise ValueError(f'{clss} class(es) not found in {module_or_file!r}.')
Expand Down
2 changes: 1 addition & 1 deletion panel/io/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ def url_path(self) -> str | None:
# TODO should fix invalid URL characters
return '/' + os.path.splitext(os.path.basename(self._runner.path))[0]

def modify_document(self, doc: 'Document'):
def modify_document(self, doc: Document):
if config.autoreload:
path = self._runner.path
argv = self._runner._argv
Expand Down
4 changes: 2 additions & 2 deletions panel/io/jupyter_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import weakref

from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Union
from typing import TYPE_CHECKING, Any

import tornado

Expand Down Expand Up @@ -182,7 +182,7 @@ def _create_server_session(self) -> tuple[ServerSession, str | None]:
return session, runner.error_detail

async def write_message( # type: ignore
self, message: Union[bytes, str, dict[str, Any]],
self, message: bytes | str | dict[str, Any],
binary: bool = False, locked: bool = True
) -> None:
metadata = {'binary': binary}
Expand Down
Loading

0 comments on commit 71912de

Please sign in to comment.