diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6d1ae3d01c..0fe49ef32f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -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: diff --git a/doc/generate_modules.py b/doc/generate_modules.py index 0ec9bfb8ae..035726a17b 100644 --- a/doc/generate_modules.py +++ b/doc/generate_modules.py @@ -57,7 +57,7 @@ def write_file(name, text, opts): """Write the output file for module/package .""" 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: @@ -69,7 +69,7 @@ def write_file(name, text, opts): def format_heading(level, text): """Create a heading of [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.""" @@ -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: @@ -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) diff --git a/examples/apps/django/sliders/sinewave.py b/examples/apps/django/sliders/sinewave.py index a95c0d2af1..c9bb88f0f3 100644 --- a/examples/apps/django/sliders/sinewave.py +++ b/examples/apps/django/sliders/sinewave.py @@ -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, diff --git a/examples/apps/django_multi_apps/gbm/pn_model.py b/examples/apps/django_multi_apps/gbm/pn_model.py index eb728b48f5..2f9baf4105 100644 --- a/examples/apps/django_multi_apps/gbm/pn_model.py +++ b/examples/apps/django_multi_apps/gbm/pn_model.py @@ -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) diff --git a/examples/apps/django_multi_apps/sliders/pn_model.py b/examples/apps/django_multi_apps/sliders/pn_model.py index 56a2e32295..4d17bdd658 100644 --- a/examples/apps/django_multi_apps/sliders/pn_model.py +++ b/examples/apps/django_multi_apps/sliders/pn_model.py @@ -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, diff --git a/examples/apps/django_multi_apps/stockscreener/pn_model.py b/examples/apps/django_multi_apps/stockscreener/pn_model.py index 787834cdbe..8916c885ba 100644 --- a/examples/apps/django_multi_apps/stockscreener/pn_model.py +++ b/examples/apps/django_multi_apps/stockscreener/pn_model.py @@ -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 diff --git a/examples/apps/django_multi_apps/stockscreener/pn_model_20122019.py b/examples/apps/django_multi_apps/stockscreener/pn_model_20122019.py index 76eb73335b..7364592bb7 100644 --- a/examples/apps/django_multi_apps/stockscreener/pn_model_20122019.py +++ b/examples/apps/django_multi_apps/stockscreener/pn_model_20122019.py @@ -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) diff --git a/examples/apps/fastApi/sliders/sinewave.py b/examples/apps/fastApi/sliders/sinewave.py index 56a2e32295..4d17bdd658 100644 --- a/examples/apps/fastApi/sliders/sinewave.py +++ b/examples/apps/fastApi/sliders/sinewave.py @@ -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, diff --git a/examples/apps/fastApi_multi_apps/sliders/sinewave.py b/examples/apps/fastApi_multi_apps/sliders/sinewave.py index 56a2e32295..4d17bdd658 100644 --- a/examples/apps/fastApi_multi_apps/sliders/sinewave.py +++ b/examples/apps/fastApi_multi_apps/sliders/sinewave.py @@ -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, diff --git a/examples/apps/fastApi_multi_apps/sliders2/sinewave.py b/examples/apps/fastApi_multi_apps/sliders2/sinewave.py index 56a2e32295..4d17bdd658 100644 --- a/examples/apps/fastApi_multi_apps/sliders2/sinewave.py +++ b/examples/apps/fastApi_multi_apps/sliders2/sinewave.py @@ -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, diff --git a/panel/chat/input.py b/panel/chat/input.py index 602941613c..71fb591865 100644 --- a/panel/chat/input.py +++ b/panel/chat/input.py @@ -1,7 +1,7 @@ from __future__ import annotations from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import param @@ -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) diff --git a/panel/chat/interface.py b/panel/chat/interface.py index 650f809f74..1e6b84b3ee 100644 --- a/panel/chat/interface.py +++ b/panel/chat/interface.py @@ -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. @@ -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. @@ -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, @@ -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 @@ -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. diff --git a/panel/chat/langchain.py b/panel/chat/langchain.py index 2182e4b114..5aa31f2ca1 100644 --- a/panel/chat/langchain.py +++ b/panel/chat/langchain.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any, Union +from typing import Any try: from langchain.callbacks.base import BaseCallbackHandler @@ -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: @@ -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) @@ -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) diff --git a/panel/chat/message.py b/panel/chat/message.py index af67993355..51587c21f0 100644 --- a/panel/chat/message.py +++ b/panel/chat/message.py @@ -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 @@ -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) diff --git a/panel/custom.py b/panel/custom.py index 6758121ec8..393dadeffb 100644 --- a/panel/custom.py +++ b/panel/custom.py @@ -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 @@ -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) @@ -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 @@ -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) @@ -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()): diff --git a/panel/io/browser.py b/panel/io/browser.py index 66fad402aa..8cdee0a5aa 100644 --- a/panel/io/browser.py +++ b/panel/io/browser.py @@ -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'] diff --git a/panel/io/cache.py b/panel/io/cache.py index e22172520a..7e80244708 100644 --- a/panel/io/cache.py +++ b/panel/io/cache.py @@ -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, diff --git a/panel/io/compile.py b/panel/io/compile.py index 3ce818ef7a..74d036d275 100644 --- a/panel/io/compile.py +++ b/panel/io/compile.py @@ -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}.') diff --git a/panel/io/handlers.py b/panel/io/handlers.py index 93ff0b6171..bf438b3f21 100644 --- a/panel/io/handlers.py +++ b/panel/io/handlers.py @@ -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 diff --git a/panel/io/jupyter_executor.py b/panel/io/jupyter_executor.py index 4eea7b2f79..80257ad367 100644 --- a/panel/io/jupyter_executor.py +++ b/panel/io/jupyter_executor.py @@ -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 @@ -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} diff --git a/panel/io/location.py b/panel/io/location.py index 0fcafc4114..1920aaaa02 100644 --- a/panel/io/location.py +++ b/panel/io/location.py @@ -7,7 +7,7 @@ import urllib.parse as urlparse from typing import ( - TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, Callable, ClassVar, Mapping, ) import param @@ -125,9 +125,9 @@ def __init__(self, **params): self.param.watch(self._update_synced, ['search']) 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: model = _BkLocation(**self._process_param_change(self._init_params())) root = root or model self._models[root.ref['id']] = (model, parent) @@ -135,9 +135,9 @@ def _get_model( return model def get_root( - self, doc: Optional[Document] = None, comm: Optional[Comm] = None, + 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'] @@ -193,7 +193,7 @@ def _update_synced(self, event: param.parameterized.Event = None) -> None: on_error(mapped) def _update_query( - self, *events: param.parameterized.Event, query: Optional[dict[str, Any]] = None + self, *events: param.parameterized.Event, query: dict[str, Any] | None = None ) -> None: if self._syncing: return @@ -226,8 +226,8 @@ def update_query(self, **kwargs: Mapping[str, Any]) -> None: self.search = '?' + urlparse.urlencode(query) def sync( - self, parameterized: param.Parameterized, parameters: Optional[list[str] | dict[str, str]] = None, - on_error: Optional[Callable[[dict[str, Any]], None]] = None + self, parameterized: param.Parameterized, parameters: list[str] | dict[str, str] | None = None, + on_error: Callable[[dict[str, Any]], None] | None = None ) -> None: """ Syncs the parameters of a Parameterized object with the query @@ -268,7 +268,7 @@ def sync( query[name] = v self._update_query(query=query) - def unsync(self, parameterized: param.Parameterized, parameters: Optional[list[str]] = None) -> None: + def unsync(self, parameterized: param.Parameterized, parameters: list[str] | None = None) -> None: """ Unsyncs the parameters of the Parameterized with the query params in the URL. If no parameters are supplied all diff --git a/panel/io/model.py b/panel/io/model.py index a75a00ed38..e1ba80d48a 100644 --- a/panel/io/model.py +++ b/panel/io/model.py @@ -7,7 +7,7 @@ from contextlib import contextmanager from typing import ( - TYPE_CHECKING, Any, Iterable, Optional, Sequence, + TYPE_CHECKING, Any, Iterable, Sequence, ) import numpy as np @@ -138,7 +138,7 @@ def patch_cds_msg(model, msg): _DEFAULT_IGNORED_REPR = frozenset(['children', 'text', 'name', 'toolbar', 'renderers', 'below', 'center', 'left', 'right']) -def bokeh_repr(obj: Model, depth: int = 0, ignored: Optional[Iterable[str]] = None) -> str: +def bokeh_repr(obj: Model, depth: int = 0, ignored: Iterable[str] | None = None) -> str: """ Returns a string repr for a bokeh model, useful for recreating panel objects using pure bokeh. diff --git a/panel/io/notebook.py b/panel/io/notebook.py index 6d3b3118ea..40af5f1235 100644 --- a/panel/io/notebook.py +++ b/panel/io/notebook.py @@ -13,7 +13,7 @@ from contextlib import contextmanager from functools import partial from typing import ( - TYPE_CHECKING, Any, Iterator, Literal, Optional, + TYPE_CHECKING, Any, Iterator, Literal, ) import bokeh @@ -167,7 +167,7 @@ def html_for_render_items(docs_json, render_items, template=None, template_varia return template.render(context) def render_template( - document: 'Document', comm: Optional['Comm'] = None, manager: Optional['CommManager'] = None + document: Document, comm: Comm | None = None, manager: CommManager | None = None ) -> tuple[dict[str, str], dict[str, dict[str, str]]]: ref = document.roots[0].ref['id'] (docs_json, render_items) = standalone_docs_json_and_render_items(document, suppress_callback_warning=True) @@ -185,7 +185,7 @@ def render_template( return ({'text/html': html, EXEC_MIME: ''}, {EXEC_MIME: {'id': ref}}) def render_model( - model: 'Model', comm: Optional['Comm'] = None, resources: str = 'cdn' + model: Model, comm: Comm | None = None, resources: str = 'cdn' ) -> tuple[dict[str, str], dict[str, dict[str, str]]]: if not isinstance(model, Model): raise ValueError("notebook_content expects a single Model instance") @@ -237,9 +237,9 @@ def _repr_mimebundle_(include=None, exclude=None): def render_mimebundle( - model: 'Model', doc: 'Document', comm: 'Comm', - manager: Optional['CommManager'] = None, - location: Optional['Location'] = None, + model: Model, doc: Document, comm: Comm, + manager: CommManager | None = None, + location: Location | None = None, resources: str = 'cdn' ) -> tuple[dict[str, str], dict[str, dict[str, str]]]: """ @@ -444,7 +444,7 @@ def load_notebook( publish_display_data(data={LOAD_MIME: JS, 'application/javascript': JS}) -def show_server(panel: Any, notebook_url: str, port: int = 0) -> 'Server': +def show_server(panel: Any, notebook_url: str, port: int = 0) -> Server: """ Displays a bokeh server inline in the notebook. @@ -494,7 +494,7 @@ def show_server(panel: Any, notebook_url: str, port: int = 0) -> 'Server': def render_embed( panel, max_states: int = 1000, max_opts: int = 3, json: bool = False, - json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, + json_prefix: str = '', save_path: str = './', load_path: str | None = None, progress: bool = True, states: dict[Widget, list[Any]] = {} ) -> Mimebundle: """ diff --git a/panel/io/resources.py b/panel/io/resources.py index effad8cc92..b69067c5b1 100644 --- a/panel/io/resources.py +++ b/panel/io/resources.py @@ -731,7 +731,7 @@ def dist_dir(self): def css_files(self): from ..config import config - files = super(Resources, self).css_files + files = super().css_files self.extra_resources(files, '__css__') css_files = self.adjust_paths([ css for css in files if self.mode != 'inline' or not is_cdn_url(css) @@ -747,7 +747,7 @@ def css_files(self): @property def css_raw(self): from ..config import config - raw = super(Resources, self).css_raw + raw = super().css_raw # Inline local dist resources css_files = self._collect_external_resources("__css__") @@ -782,7 +782,7 @@ def js_files(self): # Gather JS files with set_resource_mode(self.mode): - files = super(Resources, self).js_files + files = super().js_files self.extra_resources(files, '__javascript__') files += [js for js in config.js_files.values()] if config.design: @@ -854,7 +854,7 @@ def js_module_exports(self): @property def js_raw(self): - raw_js = super(Resources, self).js_raw + raw_js = super().js_raw if not self.mode == 'inline': return raw_js diff --git a/panel/io/server.py b/panel/io/server.py index 1e73976fa6..af455231be 100644 --- a/panel/io/server.py +++ b/panel/io/server.py @@ -17,7 +17,7 @@ from functools import partial, wraps from html import escape from typing import ( - TYPE_CHECKING, Any, Callable, Mapping, Optional, TypedDict, + TYPE_CHECKING, Any, Callable, Mapping, TypedDict, ) from urllib.parse import urlparse @@ -238,12 +238,12 @@ def html_page_for_render_items( return html def server_html_page_for_session( - session: 'ServerSession', - resources: 'Resources', + session: ServerSession, + resources: Resources, title: str, token: str | None = None, template: str | Template = BASE_TEMPLATE, - template_variables: Optional[dict[str, Any]] = None, + template_variables: dict[str, Any] | None = None, ) -> str: # ALERT: Replace with better approach before Bokeh 3.x compatible release @@ -692,12 +692,12 @@ def validate_absolute_path(self, root: str, absolute_path: str) -> str: def serve( panels: TViewableFuncOrPath | dict[str, TViewableFuncOrPath], port: int = 0, - address: Optional[str] = None, - websocket_origin: Optional[str | list[str]] = None, - loop: Optional[IOLoop] = None, + address: str | None = None, + websocket_origin: str | list[str] | None = None, + loop: IOLoop | None = None, show: bool = True, start: bool = True, - title: Optional[str] = None, + title: str | None = None, verbose: bool = True, location: bool = True, threaded: bool = False, diff --git a/panel/io/state.py b/panel/io/state.py index 978d4bc23f..2121103891 100644 --- a/panel/io/state.py +++ b/panel/io/state.py @@ -20,7 +20,7 @@ from functools import partial, wraps from typing import ( TYPE_CHECKING, Any, Callable, ClassVar, Coroutine, Hashable, - Iterator as TIterator, Literal, Optional, TypeVar, Union, + Iterator as TIterator, Literal, TypeVar, Union, ) from urllib.parse import urljoin from weakref import WeakKeyDictionary @@ -762,7 +762,7 @@ def on_session_destroyed(self, callback: Callable[[SessionContext], None]) -> No def publish( self, endpoint: str, parameterized: param.Parameterized, - parameters: Optional[list[str]] = None + parameters: list[str] | None = None ) -> None: """ Publish parameters on a Parameterized object as a REST API. diff --git a/panel/layout/base.py b/panel/layout/base.py index 2a1dc20110..e92e1a9829 100644 --- a/panel/layout/base.py +++ b/panel/layout/base.py @@ -7,7 +7,6 @@ from collections import defaultdict, namedtuple from typing import ( TYPE_CHECKING, Any, ClassVar, Generator, Iterable, Iterator, Mapping, - Optional, ) import param @@ -89,7 +88,7 @@ def __repr__(self, depth: int = 0, max_depth: int = 10) -> str: 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: msg = dict(msg) inverse = {v: k for k, v in self._property_mapping.items() if v is not None} @@ -140,7 +139,7 @@ def _update_model( def _get_objects( self, model: Model, old_objects: list[Viewable], doc: Document, - root: Model, comm: Optional[Comm] = None + root: Model, comm: Comm | None = None ): """ Returns new child models for the layout while reusing unchanged @@ -171,8 +170,8 @@ def _get_objects( return new_models, old_models 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: if self._bokeh_model is None: raise ValueError(f'{type(self).__name__} did not define a _bokeh_model.') @@ -310,7 +309,7 @@ def _compute_sizing_mode(self, children, props): #---------------------------------------------------------------- def get_root( - self, doc: Optional[Document] = None, comm: Optional[Comm] = None, + self, doc: Document | None = None, comm: Comm | None = None, preprocess: bool = True ) -> Model: root = super().get_root(doc, comm, preprocess) @@ -370,18 +369,18 @@ def __len__(self) -> int: def __iter__(self) -> Iterator[Viewable]: yield from self.objects - def __iadd__(self, other: Iterable[Any]) -> 'ListLike': + def __iadd__(self, other: Iterable[Any]) -> ListLike: self.extend(other) return self - def __add__(self, other: Iterable[Any]) -> 'ListLike': + def __add__(self, other: Iterable[Any]) -> ListLike: if isinstance(other, ListLike): other = other.objects else: other = list(other) return self.clone(*(self.objects+other)) - def __radd__(self, other: Iterable[Any]) -> 'ListLike': + def __radd__(self, other: Iterable[Any]) -> ListLike: if isinstance(other, ListLike): other = other.objects else: @@ -426,7 +425,7 @@ def __setitem__(self, index: int | slice, panes: Iterable[Any]) -> None: self.objects = new_objects - def clone(self, *objects: Any, **params: Any) -> 'ListLike': + def clone(self, *objects: Any, **params: Any) -> ListLike: """ Makes a copy of the layout sharing the same parameters. @@ -619,11 +618,11 @@ def __len__(self) -> int: def __iter__(self) -> Iterator[Viewable]: yield from self.objects - def __iadd__(self, other: Iterable[Any]) -> 'NamedListLike': + def __iadd__(self, other: Iterable[Any]) -> NamedListLike: self.extend(other) return self - def __add__(self, other: Iterable[Any]) -> 'NamedListLike': + def __add__(self, other: Iterable[Any]) -> NamedListLike: if isinstance(other, NamedListLike): added = list(zip(other._names, other.objects)) elif isinstance(other, ListLike): @@ -633,7 +632,7 @@ def __add__(self, other: Iterable[Any]) -> 'NamedListLike': objects = list(zip(self._names, self.objects)) return self.clone(*(objects+added)) - def __radd__(self, other: Iterable[Any]) -> 'NamedListLike': + def __radd__(self, other: Iterable[Any]) -> NamedListLike: if isinstance(other, NamedListLike): added = list(zip(other._names, other.objects)) elif isinstance(other, ListLike): @@ -678,7 +677,7 @@ def __setitem__(self, index: int | slice, panes: Iterable[Any]) -> None: new_objects[i], self._names[i] = self._to_object_and_name(pane) self.objects = new_objects - def clone(self, *objects: Any, **params: Any) -> 'NamedListLike': + def clone(self, *objects: Any, **params: Any) -> NamedListLike: """ Makes a copy of the Tabs sharing the same parameters. diff --git a/panel/layout/feed.py b/panel/layout/feed.py index 80017899be..05c4dd3165 100644 --- a/panel/layout/feed.py +++ b/panel/layout/feed.py @@ -1,8 +1,6 @@ from __future__ import annotations -from typing import ( - TYPE_CHECKING, ClassVar, Mapping, Optional, -) +from typing import TYPE_CHECKING, ClassVar, Mapping import param @@ -119,8 +117,8 @@ def _synced_range(self): return (0, min(self.load_buffer, n)) 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 = super()._get_model(doc, root, parent, comm) self._register_events('scroll_button_click', model=model, doc=doc, comm=comm) @@ -153,7 +151,7 @@ def _process_param_change(self, msg): def _get_objects( self, model: Model, old_objects: list[Viewable], doc: Document, - root: Model, comm: Optional[Comm] = None + root: Model, comm: Comm | None = None ): from ..pane.base import RerenderError new_models, old_models = [], [] diff --git a/panel/layout/grid.py b/panel/layout/grid.py index 345912bae0..bede7f1b99 100644 --- a/panel/layout/grid.py +++ b/panel/layout/grid.py @@ -8,7 +8,7 @@ from collections import namedtuple from functools import partial from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import numpy as np @@ -196,7 +196,7 @@ def _get_model(self, doc, root=None, parent=None, comm=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: from ..io import state diff --git a/panel/links.py b/panel/links.py index 2130cb0ca3..661dcc500a 100644 --- a/panel/links.py +++ b/panel/links.py @@ -34,7 +34,7 @@ TargetModelSpec = tuple[str | None, str | None] -def assert_source_syncable(source: 'Reactive', properties: Iterable[str]) -> None: +def assert_source_syncable(source: Reactive, properties: Iterable[str]) -> None: for prop in properties: if prop.startswith('event:'): continue @@ -69,7 +69,7 @@ def assert_source_syncable(source: 'Reactive', properties: Iterable[str]) -> Non ) def assert_target_syncable( - source: 'Reactive', target: 'JSLinkTarget', properties: dict[str, str] + source: Reactive, target: JSLinkTarget, properties: dict[str, str] ) -> None: for k, p in properties.items(): if k.startswith('event:'): @@ -183,7 +183,7 @@ def init(self) -> None: self.registry[source] = [self] @classmethod - def register_callback(cls, callback: type['CallbackGenerator']) -> None: + def register_callback(cls, callback: type[CallbackGenerator]) -> None: """ Register a LinkCallback providing the implementation for the Link for a particular backend. @@ -526,8 +526,8 @@ def _process_references(self, references): """ def _get_specs( - self, link: 'Link', source: 'Reactive', target: 'JSLinkTarget' - ) -> Sequence[tuple['SourceModelSpec', 'TargetModelSpec', str | None]]: + self, link: Link, source: Reactive, target: JSLinkTarget + ) -> Sequence[tuple[SourceModelSpec, TargetModelSpec, str | None]]: """ Return a list of spec tuples that define source and target models. @@ -535,8 +535,8 @@ def _get_specs( return [] def _get_code( - self, link: 'Link', source: 'JSLinkTarget', src_spec: str, - target: 'JSLinkTarget' | None, tgt_spec: str | None + self, link: Link, source: JSLinkTarget, src_spec: str, + target: JSLinkTarget | None, tgt_spec: str | None ) -> str: """ Returns the code to be executed. @@ -544,7 +544,7 @@ def _get_code( return '' def _get_triggers( - self, link: 'Link', src_spec: 'SourceModelSpec' + self, link: Link, src_spec: SourceModelSpec ) -> tuple[list[str], list[str]]: """ Returns the changes and events that trigger the callback. @@ -552,8 +552,8 @@ def _get_triggers( return [], [] def _initialize_models( - self, link, source: 'Reactive', src_model: 'Model', src_spec: str, - target: 'JSLinkTarget' | None, tgt_model: 'Model' | None, tgt_spec: str | None + self, link, source: Reactive, src_model: Model, src_spec: str, + target: JSLinkTarget | None, tgt_model: Model | None, tgt_spec: str | None ) -> None: """ Applies any necessary initialization to the source and target @@ -568,15 +568,15 @@ def validate(self) -> None: class JSCallbackGenerator(CallbackGenerator): def _get_triggers( - self, link: 'Link', src_spec: 'SourceModelSpec' + self, link: Link, src_spec: SourceModelSpec ) -> tuple[list[str], list[str]]: if src_spec[1].startswith('event:'): return [], [src_spec[1].split(':')[1]] return [src_spec[1]], [] def _get_specs( - self, link: 'Link', source: 'Reactive', target: 'JSLinkTarget' - ) -> Sequence[tuple['SourceModelSpec', 'TargetModelSpec', str | None]]: + self, link: Link, source: Reactive, target: JSLinkTarget + ) -> Sequence[tuple[SourceModelSpec, TargetModelSpec, str | None]]: for spec in link.code: src_specs = spec.split('.') src_spec: tuple[str | None, str] @@ -659,8 +659,8 @@ class JSLinkCallbackGenerator(JSCallbackGenerator): """ def _get_specs( - self, link: 'Link', source: 'Reactive', target: 'JSLinkTarget' - ) -> Sequence[tuple['SourceModelSpec', 'TargetModelSpec', str | None]]: + self, link: Link, source: Reactive, target: JSLinkTarget + ) -> Sequence[tuple[SourceModelSpec, TargetModelSpec, str | None]]: if link.code: return super()._get_specs(link, source, target) @@ -686,8 +686,8 @@ def _get_specs( return specs def _initialize_models( - self, link, source: 'Reactive', src_model: 'Model', src_spec: str, - target: 'JSLinkTarget' | None, tgt_model: 'Model' | None, tgt_spec: str | None + self, link, source: Reactive, src_model: Model, src_spec: str, + target: JSLinkTarget | None, tgt_model: Model | None, tgt_spec: str | None ) -> None: if tgt_model is not None and src_spec and tgt_spec: src_reverse = {v: k for k, v in getattr(source, '_rename', {}).items()} @@ -722,8 +722,8 @@ def _process_references(self, references: dict[str, str]) -> None: references[k[7:]] = references.pop(k) def _get_code( - self, link: 'Link', source: 'JSLinkTarget', src_spec: str, - target: 'JSLinkTarget' | None, tgt_spec: str | None + self, link: Link, source: JSLinkTarget, src_spec: str, + target: JSLinkTarget | None, tgt_spec: str | None ) -> str: if isinstance(source, Reactive): src_reverse = {v: k for k, v in source._rename.items()} diff --git a/panel/pane/base.py b/panel/pane/base.py index f79a8f2355..de84ace9af 100644 --- a/panel/pane/base.py +++ b/panel/pane/base.py @@ -6,7 +6,7 @@ from functools import partial from typing import ( - TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Optional, TypeVar, + TYPE_CHECKING, Any, Callable, ClassVar, Mapping, TypeVar, ) import numpy as np @@ -231,7 +231,7 @@ def applies(cls, obj: Any) -> float | bool | None: return None @classmethod - def get_pane_type(cls, obj: Any, **kwargs) -> type['PaneBase']: + def get_pane_type(cls, obj: Any, **kwargs) -> type[PaneBase]: """ Returns the applicable Pane type given an object by resolving the precedence of all types whose applies method declares that @@ -340,7 +340,7 @@ def _param_change(self, *events: param.parameterized.Event) -> None: super()._param_change(*events) def _update_object( - self, ref: str, doc: 'Document', root: Model, parent: Model, comm: Comm | None + self, ref: str, doc: Document, root: Model, parent: Model, comm: Comm | None ) -> None: old_model = self._models[ref][0] if self._updates: @@ -462,7 +462,7 @@ def _get_root_model( # Public API #---------------------------------------------------------------- - def clone(self: T, object: Optional[Any] = None, **params) -> T: + def clone(self: T, object: Any | None = None, **params) -> T: """ Makes a copy of the Pane sharing the same parameters. diff --git a/panel/pane/deckgl.py b/panel/pane/deckgl.py index 7042f400e2..4a16cae673 100644 --- a/panel/pane/deckgl.py +++ b/panel/pane/deckgl.py @@ -9,7 +9,7 @@ from collections import defaultdict from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import numpy as np @@ -276,8 +276,8 @@ def _transform_object(self, obj) -> dict[str, Any]: return dict(data=data, tooltip=tooltip, configuration=configuration, mapbox_api_key=mapbox_api_key or "") 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: self._bokeh_model = DeckGLPlot = lazy_load( 'panel.models.deckgl', 'DeckGLPlot', isinstance(comm, JupyterComm), root diff --git a/panel/pane/echarts.py b/panel/pane/echarts.py index 22fd8d9ba1..46800eb3ea 100644 --- a/panel/pane/echarts.py +++ b/panel/pane/echarts.py @@ -5,7 +5,7 @@ from collections import defaultdict from typing import ( - TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, Callable, ClassVar, Mapping, ) import param @@ -124,8 +124,8 @@ def _get_properties(self, document: Document): return props 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: self._bokeh_model = lazy_load( 'panel.models.echarts', 'ECharts', isinstance(comm, JupyterComm), root diff --git a/panel/pane/holoviews.py b/panel/pane/holoviews.py index 827d45eff8..cacf02e1eb 100644 --- a/panel/pane/holoviews.py +++ b/panel/pane/holoviews.py @@ -10,7 +10,7 @@ from collections import defaultdict from functools import partial from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import param @@ -417,8 +417,8 @@ def _process_param_change(self, params): #---------------------------------------------------------------- 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: from holoviews.plotting.plot import Plot if root is None: @@ -738,8 +738,8 @@ def _update_layout_properties(self, *events): self._layout_panel.param.update(**{e.name: e.new for e in events}) 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: if root is None: return self.get_root(doc, comm) diff --git a/panel/pane/ipywidget.py b/panel/pane/ipywidget.py index a4ca2b08ae..121999b4db 100644 --- a/panel/pane/ipywidget.py +++ b/panel/pane/ipywidget.py @@ -2,9 +2,7 @@ import os -from typing import ( - TYPE_CHECKING, Any, ClassVar, Optional, -) +from typing import TYPE_CHECKING, Any, ClassVar import param @@ -71,8 +69,8 @@ def _get_ipywidget(self, obj, doc, root, comm, **kwargs): return model 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: if root is None: return self.get_root(doc, comm) @@ -115,7 +113,7 @@ def _cleanup(self, root: Model | None = None) -> None: super()._cleanup(root) def _get_ipywidget( - self, obj, doc: Document, root: Model, comm: Optional[Comm], **kwargs + self, obj, doc: Document, root: Model, comm: Comm | None, **kwargs ): if not isinstance(comm, JupyterComm) or "PANEL_IPYWIDGET" in os.environ: from ..io.ipywidget import Widget # noqa diff --git a/panel/pane/perspective.py b/panel/pane/perspective.py index 476a9e3904..e5a6ef44b0 100644 --- a/panel/pane/perspective.py +++ b/panel/pane/perspective.py @@ -6,7 +6,7 @@ from enum import Enum from functools import partial from typing import ( - TYPE_CHECKING, Callable, ClassVar, Mapping, Optional, + TYPE_CHECKING, Callable, ClassVar, Mapping, ) import numpy as np @@ -364,7 +364,7 @@ def _get_data(self): k: v for k, v in kwargs.items() if getattr(self, k) is None }) - cols = set(self._as_digit(c) for c in df) + cols = {self._as_digit(c) for c in df} if len(cols) != ncols: raise ValueError("Integer columns must be unique when " "converted to strings.") @@ -475,8 +475,8 @@ def _process_property_change(self, msg): return msg 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: self._bokeh_model = lazy_load( 'panel.models.perspective', 'Perspective', isinstance(comm, JupyterComm), root diff --git a/panel/pane/plot.py b/panel/pane/plot.py index 8b83769eb7..f2fc7a1151 100644 --- a/panel/pane/plot.py +++ b/panel/pane/plot.py @@ -10,7 +10,7 @@ from functools import partial from io import BytesIO from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import param @@ -162,8 +162,8 @@ def _sync_properties(self): self._syncing_props = False 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: if root is None: return self.get_root(doc, comm) @@ -319,8 +319,8 @@ def _transform_object(self, obj: Any) -> dict[str, Any]: return self._img_type._transform_object(self, obj) 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: if not self.interactive: return self._img_type._get_model(self, doc, root, parent, comm) diff --git a/panel/pane/plotly.py b/panel/pane/plotly.py index 8b15d81439..846ea92111 100644 --- a/panel/pane/plotly.py +++ b/panel/pane/plotly.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import numpy as np @@ -311,8 +311,8 @@ def _process_param_change(self, params): return props 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: if not hasattr(self, '_bokeh_model'): self._bokeh_model = lazy_load( diff --git a/panel/pane/streamz.py b/panel/pane/streamz.py index c4cbc63641..e8fd4676a4 100644 --- a/panel/pane/streamz.py +++ b/panel/pane/streamz.py @@ -6,7 +6,7 @@ import sys from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import param @@ -58,8 +58,8 @@ def _setup_stream(self): self._stream.sink(self._update_inner) 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 = super()._get_model(doc, root, parent, comm) self._setup_stream() diff --git a/panel/pane/vega.py b/panel/pane/vega.py index 3ad207eeba..51f7ba2c8b 100644 --- a/panel/pane/vega.py +++ b/panel/pane/vega.py @@ -4,7 +4,7 @@ import sys from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import numpy as np @@ -32,7 +32,7 @@ def ds_as_cds(dataset): if len(dataset) == 0: return {} # create a list of unique keys from all items as some items may not include optional fields - keys = sorted(set(k for d in dataset for k in d.keys())) + keys = sorted({k for d in dataset for k in d.keys()}) data = {k: [] for k in keys} for item in dataset: for k in keys: @@ -286,8 +286,8 @@ def _get_properties(self, doc, sources={}): return props 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: self._bokeh_model = lazy_load( 'panel.models.vega', 'VegaPlot', isinstance(comm, JupyterComm), root diff --git a/panel/pane/vizzu.py b/panel/pane/vizzu.py index 38be1ca570..104964661f 100644 --- a/panel/pane/vizzu.py +++ b/panel/pane/vizzu.py @@ -4,7 +4,7 @@ import sys from typing import ( - TYPE_CHECKING, Any, Callable, ClassVar, Optional, + TYPE_CHECKING, Any, Callable, ClassVar, ) import numpy as np @@ -149,8 +149,8 @@ def _process_param_change(self, params): return super()._process_param_change(params) 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: self._bokeh_model = lazy_load( 'panel.models.vizzu', 'VizzuChart', isinstance(comm, JupyterComm), root diff --git a/panel/pane/vtk/vtk.py b/panel/pane/vtk/vtk.py index 99b22ec452..ff039d0227 100644 --- a/panel/pane/vtk/vtk.py +++ b/panel/pane/vtk/vtk.py @@ -10,7 +10,7 @@ from abc import abstractmethod from typing import ( - IO, TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + IO, TYPE_CHECKING, Any, ClassVar, Mapping, ) from urllib.request import urlopen @@ -83,7 +83,7 @@ def _process_param_change(self, msg): 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: if 'axes' in msg and msg['axes'] is not None: VTKAxes = sys.modules['panel.models.vtk'].VTKAxes @@ -376,14 +376,14 @@ def applies(cls, obj, **kwargs): serialize_on_instantiation) def __init__(self, object=None, **params): - super(VTKRenderWindow, self).__init__(object, **params) + super().__init__(object, **params) if object is not None: self.color_mappers = self.get_color_mappers() self._update(None, None) 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: VTKSynchronizedPlot = lazy_load( 'panel.models.vtk', 'VTKSynchronizedPlot', isinstance(comm, JupyterComm), root @@ -443,8 +443,8 @@ def __init__(self, object=None, **params): self._contexts = {} 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: VTKSynchronizedPlot = lazy_load( 'panel.models.vtk', 'VTKSynchronizedPlot', isinstance(comm, JupyterComm), root @@ -661,8 +661,8 @@ def applies(cls, obj: Any) -> float | bool | None: return isinstance(obj, vtk.vtkImageData) 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: VTKVolumePlot = lazy_load( 'panel.models.vtk', 'VTKVolumePlot', isinstance(comm, JupyterComm), root @@ -834,8 +834,8 @@ def applies(cls, obj: Any) -> float | bool | None: return True 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: """ Should return the bokeh model to be rendered. diff --git a/panel/param.py b/panel/param.py index fc0d204156..83447caf77 100644 --- a/panel/param.py +++ b/panel/param.py @@ -18,7 +18,7 @@ from contextlib import contextmanager from functools import partial from typing import ( - TYPE_CHECKING, Any, ClassVar, Generator, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Generator, Mapping, ) import param @@ -77,13 +77,13 @@ def SingleFileSelector(pobj: param.Parameter) -> type[Widget]: def LiteralInputTyped(pobj: param.Parameter) -> type[Widget]: if isinstance(pobj, param.Tuple): - return type(str('TupleInput'), (LiteralInput,), {'type': tuple}) + return type('TupleInput', (LiteralInput,), {'type': tuple}) elif isinstance(pobj, param.Number): - return type(str('NumberInput'), (LiteralInput,), {'type': (int, float)}) + return type('NumberInput', (LiteralInput,), {'type': (int, float)}) elif isinstance(pobj, param.Dict): - return type(str('DictInput'), (LiteralInput,), {'type': dict}) + return type('DictInput', (LiteralInput,), {'type': dict}) elif isinstance(pobj, param.List): - return type(str('ListInput'), (LiteralInput,), {'type': list}) + return type('ListInput', (LiteralInput,), {'type': list}) return LiteralInput @@ -715,8 +715,8 @@ def _get_widgets(self): return dict(widgets) 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.layout._get_model(doc, root, parent, comm) self._models[root.ref['id']] = (model, parent) @@ -750,7 +750,7 @@ def widget_type(cls, pobj): return wtype def get_root( - self, doc: Optional[Document] = None, comm: Comm | None = None, + self, doc: Document | None = None, comm: Comm | None = None, preprocess: bool = True ) -> Model: root = super().get_root(doc, comm, preprocess) @@ -912,8 +912,8 @@ def _update_pane(self, *events): self._replace_pane() 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: if not self._evaled: deferred = self.defer_load and not state.loaded @@ -1229,9 +1229,9 @@ def widgets(self): return self.widget_layout(*widgets) 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: return self.layout._get_model(doc, root, parent, comm) def _generate_layout(self): @@ -1304,7 +1304,7 @@ def __call__(self, parameterized): if self.json_file or env_var.endswith('.json'): try: fname = self.json_file if self.json_file else env_var - with open(fullpath(fname), 'r') as f: + with open(fullpath(fname)) as f: spec = json.load(f) except Exception: warnobj.warning(f'Could not load JSON file {spec!r}') diff --git a/panel/reactive.py b/panel/reactive.py index 5b56b20138..7c02f08d3b 100644 --- a/panel/reactive.py +++ b/panel/reactive.py @@ -19,7 +19,7 @@ from functools import lru_cache, partial from pprint import pformat from typing import ( - TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Optional, Sequence, Union, + TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Sequence, Union, ) import jinja2 @@ -263,7 +263,7 @@ def _link_params(self) -> None: def _link_props( self, model: Model | DataModel, properties: Sequence[str] | Sequence[tuple[str, str]], - doc: Document, root: Model, comm: Optional[Comm] = None + doc: Document, root: Model, comm: Comm | None = None ) -> None: from .config import config ref = root.ref['id'] @@ -288,7 +288,7 @@ def _link_props( def _manual_update( self, events: tuple[param.parameterized.Event, ...], model: Model, doc: Document, - root: Model, parent: Optional[Model], comm: Optional[Comm] + root: Model, parent: Model | None, comm: Comm | None ) -> None: """ Method for handling any manual update events, i.e. events triggered @@ -314,7 +314,7 @@ def _update_manual(self, *events: param.parameterized.Event) -> None: def _scheduled_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, curdoc_events: dict[str, Any] ) -> None: # @@ -345,7 +345,7 @@ def _apply_update( 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: ref = root.ref['id'] self._changing[ref] = attrs = [] @@ -695,7 +695,7 @@ def _update_properties(self, *events: param.parameterized.Event, doc: Document) 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: if 'stylesheets' in msg: if doc and 'dist_url' in doc._template_variables: @@ -712,7 +712,7 @@ def _update_model( #---------------------------------------------------------------- def link( - self, target: param.Parameterized, callbacks: Optional[dict[str, str | Callable]]=None, + self, target: param.Parameterized, callbacks: dict[str, str | Callable] | None=None, bidirectional: bool=False, **links: str ) -> Watcher: """ @@ -1027,7 +1027,7 @@ def _update_data(self, data: TData) -> None: def _manual_update( self, events: tuple[param.parameterized.Event, ...], model: Model, - doc: Document, root: Model, parent: Optional[Model], comm: Comm + doc: Document, root: Model, parent: Model | None, comm: Comm ) -> None: for event in events: if event.type == 'triggered' and self._updating: @@ -1219,7 +1219,7 @@ def stream( else: raise ValueError("The stream value provided is not a DataFrame, Series or Dict!") - def patch(self, patch_value: 'pd.DataFrame' | 'pd.Series' | dict) -> None: + def patch(self, patch_value: pd.DataFrame | pd.Series | dict) -> None: """ Efficiently patches (updates) the existing value with the `patch_value`. @@ -1329,7 +1329,7 @@ def _update_selection(self, indices: list[int]) -> None: self.selection = indices def _convert_column( - self, values: np.ndarray, old_values: np.ndarray | 'pd.Series' + self, values: np.ndarray, old_values: np.ndarray | pd.Series ) -> np.ndarray | list: dtype = old_values.dtype converted: list | np.ndarray | None = None @@ -1442,7 +1442,7 @@ def _process_events(self, events: dict[str, Any]) -> None: self._update_selection(events.pop('indices')) finally: self._updating = False - super(ReactiveData, self)._process_events(events) + super()._process_events(events) class ReactiveMetaBase(ParameterizedMetaclass): @@ -1563,11 +1563,11 @@ def __init__(mcs, name: str, bases: tuple[type, ...], dict_: Mapping[str, Any]): class ReactiveCustomBase(Reactive): - _extension_name: ClassVar[Optional[str]] = None + _extension_name: ClassVar[str | None] = None - __css__: ClassVar[Optional[list[str]]] = None - __javascript__: ClassVar[Optional[list[str]]] = None - __javascript_modules__: ClassVar[Optional[list[str]]] = None + __css__: ClassVar[list[str] | None] = None + __javascript__: ClassVar[list[str] | None] = None + __javascript_modules__: ClassVar[list[str] | None] = None @classmethod def _loaded(cls) -> bool: @@ -1841,7 +1841,7 @@ def _child_names(self): return {} def _process_children( - self, doc: Document, root: Model, model: Model, comm: Optional[Comm], + self, doc: Document, root: Model, model: Model, comm: Comm | None, children: dict[str, list[Model]] ) -> dict[str, list[Model]]: return children @@ -1918,7 +1918,7 @@ def _get_events(self) -> dict[str, dict[str, bool]]: return events def _get_children( - self, doc: Document, root: Model, model: Model, comm: Optional[Comm] + self, doc: Document, root: Model, model: Model, comm: Comm | None ) -> dict[str, list[Model]]: from .pane import panel old_models = model.children @@ -2082,8 +2082,8 @@ def _patch_datamodel_ref(cls, props, ref): props.tags.append(f"__ref:{ref}") 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 = _BkReactiveHTML(**self._get_properties(doc)) if comm and not self._loaded(): @@ -2118,7 +2118,7 @@ def _get_model( self._models[root.ref['id']] = (model, parent) return model - def _process_event(self, event: 'Event') -> None: + def _process_event(self, event: Event) -> None: if not isinstance(event, DOMEvent): return cb = getattr(self, f"_{event.node}_{event.data['type']}", None) @@ -2148,7 +2148,7 @@ def _set_on_model(self, msg: Mapping[str, Any], root: Model, model: Model) -> No 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: child_params = self._parser.children.values() new_children, model_msg, data_msg = {}, {}, {} diff --git a/panel/template/base.py b/panel/template/base.py index c715d9f64d..e7df1bcdec 100644 --- a/panel/template/base.py +++ b/panel/template/base.py @@ -11,7 +11,7 @@ from functools import partial from pathlib import Path, PurePath from typing import ( - IO, TYPE_CHECKING, Any, ClassVar, Literal, Optional, + IO, TYPE_CHECKING, Any, ClassVar, Literal, ) import jinja2 @@ -111,7 +111,7 @@ class BaseTemplate(param.Parameterized, MimeRenderMixin, ServableMixin, Resource def __init__( self, template: str | _Template, items=None, - nb_template: Optional[str | _Template] = None, **params + nb_template: str | _Template | None = None, **params ): config_params = { p: v for p, v in params.items() if p in _base_config.param @@ -186,8 +186,8 @@ def _server_destroy(self, session_context: BokehSessionContext): self._documents.remove(doc) def _init_doc( - self, doc: Optional[Document] = None, comm: Optional[Comm] = None, - title: Optional[str] = None, notebook: bool = False, + self, doc: Document | None = None, comm: Comm | None = None, + title: str | None = None, notebook: bool = False, location: bool | Location = True ): # Initialize document @@ -439,10 +439,10 @@ def resolve_resources( return resource_types def save( - self, filename: str | os.PathLike | IO, title: Optional[str] = None, + self, filename: str | os.PathLike | IO, title: str | None = None, resources=None, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str='', - save_path: str='./', load_path: Optional[str] = None + save_path: str='./', load_path: str | None = None ) -> None: """ Saves Panel objects to file. @@ -480,7 +480,7 @@ def save( ) def server_doc( - self, doc: Optional[Document] = None, title: str = None, + self, doc: Document | None = None, title: str = None, location: bool | Location = True ) -> Document: """ @@ -505,8 +505,8 @@ def server_doc( return self._init_doc(doc, title=title, location=location) def servable( - self, title: Optional[str] = None, location: bool | Location = True, - area: str = 'main', target: Optional[str] = None + self, title: str | None = None, location: bool | Location = True, + area: str = 'main', target: str | None = None ) -> BaseTemplate: """ Serves the template and returns self to allow it to display @@ -751,8 +751,8 @@ def __init__(self, **params): self.modal.param.trigger('objects') def _init_doc( - self, doc: Optional[Document] = None, comm: Optional['Comm'] = None, - title: Optional[str]=None, notebook: bool = False, location: bool | Location = True + self, doc: Document | None = None, comm: Comm | None = None, + title: str | None=None, notebook: bool = False, location: bool | Location = True ) -> Document: title = self.title if self.title != self.param.title.default else title if self.busy_indicator: @@ -942,7 +942,7 @@ class Template(BaseTemplate): def __init__( self, template: str | _Template, nb_template: str | _Template | None = None, - items: Optional[dict[str, Any]] = None, **params + items: dict[str, Any] | None = None, **params ): super().__init__(template=template, nb_template=nb_template, items=items, **params) items = {} if items is None else items diff --git a/panel/template/editable/__init__.py b/panel/template/editable/__init__.py index d919e4073a..21061ab66d 100644 --- a/panel/template/editable/__init__.py +++ b/panel/template/editable/__init__.py @@ -5,7 +5,7 @@ import pathlib -from typing import TYPE_CHECKING, ClassVar, Optional +from typing import TYPE_CHECKING, ClassVar import param @@ -123,8 +123,8 @@ def _update_vars(self): super()._update_vars() def _init_doc( - self, doc: Optional[Document] = None, comm: Optional[Comm] = None, - title: Optional[str] = None, notebook: bool = False, + self, doc: Document | None = None, comm: Comm | None = None, + title: str | None = None, notebook: bool = False, location: bool | Location = True ): doc = super()._init_doc(doc, comm, title, notebook, location) diff --git a/panel/tests/chat/test_langchain.py b/panel/tests/chat/test_langchain.py index 4b9a4b6c4f..b510acb182 100644 --- a/panel/tests/chat/test_langchain.py +++ b/panel/tests/chat/test_langchain.py @@ -1,4 +1,3 @@ - from unittest.mock import MagicMock, patch import pytest diff --git a/panel/tests/conftest.py b/panel/tests/conftest.py index ce4e06dd00..bc86bf99ec 100644 --- a/panel/tests/conftest.py +++ b/panel/tests/conftest.py @@ -68,7 +68,7 @@ def internet_available(host="8.8.8.8", port=53, timeout=3): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as conn: conn.connect((host, port)) return True - except socket.error: + except OSError: return False def port_open(port): diff --git a/panel/tests/io/test_document.py b/panel/tests/io/test_document.py index fafbc5e7a2..b935ad5d6e 100644 --- a/panel/tests/io/test_document.py +++ b/panel/tests/io/test_document.py @@ -1,5 +1,3 @@ - - from panel.io.document import unlocked from panel.io.state import set_curdoc from panel.tests.util import serve_and_request diff --git a/panel/tests/manual/models.py b/panel/tests/manual/models.py index 2726649336..6b88eb8563 100644 --- a/panel/tests/manual/models.py +++ b/panel/tests/manual/models.py @@ -118,7 +118,7 @@ # Model: katex latex1 = pn.pane.LaTeX( - "The LaTeX pane supports two delimiters: $LaTeX$ and \(LaTeX\)", + r"The LaTeX pane supports two delimiters: $LaTeX$ and \(LaTeX\)", styles={"font-size": "18pt"}, width=800, ) @@ -127,7 +127,7 @@ # Model: mathjax latex2 = pn.pane.LaTeX( - "$\sum_{j}{\sum_{i}{a*w_{j, i}}}$", renderer="mathjax", styles={"font-size": "18pt"} + r"$\sum_{j}{\sum_{i}{a*w_{j, i}}}$", renderer="mathjax", styles={"font-size": "18pt"} ) # Model: perspective diff --git a/panel/tests/test_models.py b/panel/tests/test_models.py index c6af59eea4..d81589cdf1 100644 --- a/panel/tests/test_models.py +++ b/panel/tests/test_models.py @@ -7,5 +7,5 @@ def test_models_encoding(): model_dir = os.path.join(panel.__path__[0], 'models') for file in os.listdir(model_dir): if file.endswith('.ts'): - with open(os.path.join(model_dir, file), 'r') as f: + with open(os.path.join(model_dir, file)) as f: f.read() diff --git a/panel/tests/ui/layout/test_gridspec.py b/panel/tests/ui/layout/test_gridspec.py index faacf4431e..15c0f0ae9a 100644 --- a/panel/tests/ui/layout/test_gridspec.py +++ b/panel/tests/ui/layout/test_gridspec.py @@ -1,4 +1,3 @@ - import pytest from panel import Column, GridSpec, Spacer diff --git a/panel/viewable.py b/panel/viewable.py index 5509078cee..fe57f96dd8 100644 --- a/panel/viewable.py +++ b/panel/viewable.py @@ -21,7 +21,7 @@ import uuid from typing import ( - IO, TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Optional, + IO, TYPE_CHECKING, Any, Callable, ClassVar, Mapping, ) import param # type: ignore @@ -359,7 +359,7 @@ def _add_location( def servable( self, title: str | None = None, location: bool | Location = True, area: str = 'main', target: str | None = None - ) -> 'ServableMixin': + ) -> ServableMixin: """ Serves the object or adds it to the configured pn.state.template if in a `panel serve` context, writes to the @@ -601,7 +601,7 @@ def _cleanup(self, root: Model | None = None) -> None: if ref in state._handles: del state._handles[ref] - def _preprocess(self, root: 'Model', changed=None, old_models=None) -> None: + def _preprocess(self, root: Model, changed=None, old_models=None) -> None: """ Applies preprocessing hooks to the root model. @@ -712,7 +712,7 @@ class Viewable(Renderable, Layoutable, ServableMixin): Whether or not the Viewable is loading. If True a loading spinner is shown on top of the Viewable.""") - _preprocessing_hooks: ClassVar[list[Callable[['Viewable', 'Model'], None]]] = [] + _preprocessing_hooks: ClassVar[list[Callable[[Viewable, Model], None]]] = [] def __init__(self, **params): hooks = params.pop('hooks', []) @@ -856,7 +856,7 @@ def __str__(self) -> str: # Public API #---------------------------------------------------------------- - def clone(self, **params) -> 'Viewable': + def clone(self, **params) -> Viewable: """ Makes a copy of the object sharing the same parameters. @@ -931,11 +931,11 @@ def embed( ) def save( - self, filename: str | os.PathLike | IO, title: Optional[str] = None, + self, filename: str | os.PathLike | IO, title: str | None = None, resources: Resources | None = None, template: str | Template | None = None, template_variables: dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, - json_prefix: str='', save_path: str='./', load_path: Optional[str] = None, + json_prefix: str='', save_path: str='./', load_path: str | None = None, progress: bool = True, embed_states: dict[Any, Any] = {}, as_png: bool | None = None, **kwargs ) -> None: @@ -1071,18 +1071,18 @@ def _create_view(self): return view def servable( - self, title: Optional[str]=None, location: bool | 'Location' = True, - area: str = 'main', target: Optional[str] = None + self, title: str | None=None, location: bool | Location = True, + area: str = 'main', target: str | None = None ) -> Viewable: return self._create_view().servable(title, location, area, target) servable.__doc__ = ServableMixin.servable.__doc__ def show( - self, title: Optional[str] = None, port: int = 0, address: Optional[str] = None, - websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, - open: bool = True, location: bool | 'Location' = True, **kwargs - ) -> threading.Thread | 'Server': + self, title: str | None = None, port: int = 0, address: str | None = None, + websocket_origin: str | None = None, threaded: bool = False, verbose: bool = True, + open: bool = True, location: bool | Location = True, **kwargs + ) -> threading.Thread | Server: return self._create_view().show( title, port, address, websocket_origin, threaded, verbose, open, location, **kwargs diff --git a/panel/widgets/base.py b/panel/widgets/base.py index 40c14dbdb1..746804dcfa 100644 --- a/panel/widgets/base.py +++ b/panel/widgets/base.py @@ -8,7 +8,7 @@ import math from typing import ( - TYPE_CHECKING, Any, Callable, ClassVar, Mapping, Optional, TypeVar, + TYPE_CHECKING, Any, Callable, ClassVar, Mapping, TypeVar, ) import param # type: ignore @@ -145,8 +145,8 @@ def _process_param_change(self, params: dict[str, Any]) -> dict[str, Any]: return params 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._widget_type(**self._get_properties(doc)) root = root or model @@ -155,8 +155,8 @@ def _get_model( return model def _get_embed_state( - self, root: 'Model', values: Optional[list[Any]] = None, max_opts: int = 3 - ) -> tuple['Widget', 'Model', list[Any], Callable[['Model'], Any], str, str]: + self, root: Model, values: list[Any] | None = None, max_opts: int = 3 + ) -> tuple[Widget, Model, list[Any], Callable[[Model], Any], str, str]: """ Returns the bokeh model and a discrete set of value states for the widget. @@ -222,7 +222,7 @@ def _update_layout_params(self, *events: param.parameterized.Event) -> None: self._composite.param.update(**updates) def select( - self, selector: Optional[type | Callable[['Viewable'], bool]] = None + self, selector: type | Callable[[Viewable], bool] | None = None ) -> list[Viewable]: """ Iterates over the Viewable and any potential children in the @@ -248,8 +248,8 @@ def _cleanup(self, root: Model | None = None) -> None: super()._cleanup(root) 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._composite._get_model(doc, root, parent, comm) root = model if root is None else root diff --git a/panel/widgets/button.py b/panel/widgets/button.py index 344b3841f7..b925845571 100644 --- a/panel/widgets/button.py +++ b/panel/widgets/button.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import ( - TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Mapping, ) import param @@ -95,8 +95,8 @@ class _ClickButton(Widget): _event: ClassVar[str] = 'button_click' 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 = super()._get_model(doc, root, parent, comm) self._register_events(self._event, model=model, doc=doc, comm=comm) @@ -200,8 +200,8 @@ def _linkable_params(self) -> list[str]: return super()._linkable_params + ['value'] def jslink( - self, target: JSLinkTarget, code: Optional[dict[str, str]] = None, - args: Optional[dict[str, Any]] = None, bidirectional: bool = False, + self, target: JSLinkTarget, code: dict[str, str] | None = None, + args: dict[str, Any] | None = None, bidirectional: bool = False, **links: str ) -> Link: """ @@ -342,8 +342,8 @@ def __init__(self, **params): self.on_click(click_handler) 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 = super()._get_model(doc, root, parent, comm) self._register_events('button_click', model=model, doc=doc, comm=comm) diff --git a/panel/widgets/codeeditor.py b/panel/widgets/codeeditor.py index 7549ad2ce7..78e1a08d7a 100644 --- a/panel/widgets/codeeditor.py +++ b/panel/widgets/codeeditor.py @@ -3,9 +3,7 @@ """ from __future__ import annotations -from typing import ( - TYPE_CHECKING, ClassVar, Mapping, Optional, -) +from typing import TYPE_CHECKING, ClassVar, Mapping import param @@ -77,8 +75,8 @@ def _update_value_input(self): self.value_input = self.value 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: if self._widget_type is None: self._widget_type = lazy_load( diff --git a/panel/widgets/debugger.py b/panel/widgets/debugger.py index 6ff246bf4e..34e96da551 100644 --- a/panel/widgets/debugger.py +++ b/panel/widgets/debugger.py @@ -94,9 +94,9 @@ def filter(self,record): if state.curdoc and state.curdoc.session_context: session_id = state.curdoc.session_context.id - widget_session_ids = set(m.document.session_context.id + widget_session_ids = {m.document.session_context.id for m in sum(self.debugger._models.values(), - tuple()) if m.document.session_context) + tuple()) if m.document.session_context} if session_id not in widget_session_ids: return False diff --git a/panel/widgets/file_selector.py b/panel/widgets/file_selector.py index 98fc6158e6..d8bc561ac9 100644 --- a/panel/widgets/file_selector.py +++ b/panel/widgets/file_selector.py @@ -7,7 +7,7 @@ import os from fnmatch import fnmatch -from typing import AnyStr, ClassVar, Optional +from typing import AnyStr, ClassVar import param @@ -200,7 +200,7 @@ def _refresh(self): self._update_files(refresh=True) def _update_files( - self, event: Optional[param.parameterized.Event] = None, refresh: bool = False + self, event: param.parameterized.Event | None = None, refresh: bool = False ): path = fullpath(self._directory.value) refresh = refresh or (event and getattr(event, 'obj', None) is self._reload) @@ -293,7 +293,7 @@ def _go_forward(self, event: param.parameterized.Event): self._directory.value = self._stack[self._position] self._update_files() - def _go_up(self, event: Optional[param.parameterized.Event] = None): + def _go_up(self, event: param.parameterized.Event | None = None): path = self._cwd.split(os.path.sep) self._directory.value = os.path.sep.join(path[:-1]) or os.path.sep self._update_files(True) diff --git a/panel/widgets/indicators.py b/panel/widgets/indicators.py index 372cd9a722..33db3c188b 100644 --- a/panel/widgets/indicators.py +++ b/panel/widgets/indicators.py @@ -25,7 +25,7 @@ from math import pi from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import numpy as np @@ -135,7 +135,7 @@ async def schedule_off(): 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: events = self._throttle_events(events) if not events: @@ -1350,8 +1350,8 @@ def __init__(self, **params): self._lock = params.pop('lock', None) 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.layout._get_model(doc, root, parent, comm) root = root or model diff --git a/panel/widgets/input.py b/panel/widgets/input.py index a7dd347568..e21f03a162 100644 --- a/panel/widgets/input.py +++ b/panel/widgets/input.py @@ -10,7 +10,7 @@ from base64 import b64decode from datetime import date, datetime, time as dt_time from typing import ( - TYPE_CHECKING, Any, ClassVar, Iterable, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Iterable, Mapping, ) import numpy as np @@ -111,8 +111,8 @@ class TextInput(_TextInputBase): _rename = {'enter_pressed': None} 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 = super()._get_model(doc, root, parent, comm) self._register_events('enter-pressed', model=model, doc=doc, comm=comm) @@ -379,8 +379,8 @@ def __init__(self, **params): self._file_buffer = {} 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: self._widget_type = lazy_load( 'panel.models.file_dropper', 'FileDropper', isinstance(comm, JupyterComm), root, @@ -1009,7 +1009,7 @@ def _linked_properties(self) -> tuple[str, ...]: 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: if 'value_throttled' in msg: del msg['value_throttled'] diff --git a/panel/widgets/select.py b/panel/widgets/select.py index bbccae86b5..6b69b23217 100644 --- a/panel/widgets/select.py +++ b/panel/widgets/select.py @@ -10,7 +10,7 @@ from functools import partial from types import FunctionType from typing import ( - TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Mapping, ) import numpy as np @@ -798,8 +798,8 @@ def __init__(self, **params): self._dbl__click_handlers = [click_handler] if click_handler else [] 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 = super()._get_model(doc, root, parent, comm) self._register_events('dblclick_event', model=model, doc=doc, comm=comm) diff --git a/panel/widgets/slider.py b/panel/widgets/slider.py index a2cc5b7837..1367138189 100644 --- a/panel/widgets/slider.py +++ b/panel/widgets/slider.py @@ -10,7 +10,7 @@ import datetime as dt from typing import ( - TYPE_CHECKING, Any, ClassVar, Mapping, Optional, + TYPE_CHECKING, Any, ClassVar, Mapping, ) import numpy as np @@ -97,7 +97,7 @@ def _process_property_change(self, msg): 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: if 'value_throttled' in msg: del msg['value_throttled'] diff --git a/panel/widgets/tables.py b/panel/widgets/tables.py index 342493842e..291879a09b 100644 --- a/panel/widgets/tables.py +++ b/panel/widgets/tables.py @@ -7,7 +7,7 @@ from types import FunctionType, MethodType from typing import ( TYPE_CHECKING, Any, Callable, ClassVar, Literal, Mapping, NotRequired, - Optional, TypedDict, + TypedDict, ) import numpy as np @@ -379,8 +379,8 @@ def _get_properties(self, doc: Document) -> dict[str, Any]: return properties 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: properties = self._get_properties(doc) model = self._widget_type(**properties) @@ -399,7 +399,7 @@ def _update_columns(self, event: param.parameterized.Event, model: Model): def _manual_update( self, events: tuple[param.parameterized.Event, ...], model: Model, doc: Document, - root: Model, parent: Optional[Model], comm: Optional[Comm] + root: Model, parent: Model | None, comm: Comm | None ) -> None: for event in events: if event.type == 'triggered' and self._updating: @@ -1841,8 +1841,8 @@ def _process_param_change(self, params): return params 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: Tabulator._widget_type = lazy_load( 'panel.models.tabulator', 'DataTabulator', isinstance(comm, JupyterComm), root @@ -2160,7 +2160,7 @@ def on_edit(self, callback: Callable[[TableEditEvent], None]): """ self._on_edit_callbacks.append(callback) - def on_click(self, callback: Callable[[CellClickEvent], None], column: Optional[str] = None): + def on_click(self, callback: Callable[[CellClickEvent], None], column: str | None = None): """ Register a callback to be executed when any cell is clicked. The callback is given a CellClickEvent declaring the column diff --git a/panel/widgets/text_to_speech.py b/panel/widgets/text_to_speech.py index de84d43df3..895e0fe01d 100644 --- a/panel/widgets/text_to_speech.py +++ b/panel/widgets/text_to_speech.py @@ -68,7 +68,7 @@ def group_by_lang(voices): if not voices: return {} - sorted_lang = sorted(list(set(voice.lang for voice in voices))) + sorted_lang = sorted(list({voice.lang for voice in voices})) result = {lang: [] for lang in sorted_lang} for voice in voices: result[voice.lang].append(voice) diff --git a/panel/widgets/texteditor.py b/panel/widgets/texteditor.py index 12c2e5ae11..00e86bb7a8 100644 --- a/panel/widgets/texteditor.py +++ b/panel/widgets/texteditor.py @@ -3,9 +3,7 @@ """ from __future__ import annotations -from typing import ( - TYPE_CHECKING, ClassVar, Mapping, Optional, -) +from typing import TYPE_CHECKING, ClassVar, Mapping import param @@ -53,8 +51,8 @@ class TextEditor(Widget): } 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: if self._widget_type is None: self._widget_type = lazy_load( diff --git a/panel/widgets/widget.py b/panel/widgets/widget.py index 30d1fb7404..0e0797d162 100644 --- a/panel/widgets/widget.py +++ b/panel/widgets/widget.py @@ -3,7 +3,7 @@ from collections.abc import Iterable, Mapping from inspect import Parameter from numbers import Integral, Number, Real -from typing import Any, Optional +from typing import Any empty = Parameter.empty @@ -37,7 +37,7 @@ def get_interact_value(self): def _get_min_max_value( - min: Number, max: Number, value: Optional[Number] = None, step: Optional[Number] = None + min: Number, max: Number, value: Number | None = None, step: Number | None = None ) -> tuple[Number, Number, Number]: """Return min, max, value given input values with possible None.""" # Either min and max need to be given, or value needs to be given diff --git a/scripts/panelite/generate_panelite_content.py b/scripts/panelite/generate_panelite_content.py index a6251e8cc4..6af41e006a 100644 --- a/scripts/panelite/generate_panelite_content.py +++ b/scripts/panelite/generate_panelite_content.py @@ -19,7 +19,7 @@ BASE_DEPENDENCIES = [] MINIMUM_VERSIONS = {} -INLINE_DIRECTIVE = re.compile('\{.*\}`.*`\s*') +INLINE_DIRECTIVE = re.compile(r'\{.*\}`.*`\s*') # Add piplite command to notebooks with open(DOC_DIR / 'pyodide_dependencies.json', encoding='utf8') as file: