Skip to content

Commit

Permalink
Ruff bugbear (#5952)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxbro authored Dec 27, 2023
1 parent 181b5ca commit 5b5dda6
Show file tree
Hide file tree
Showing 34 changed files with 103 additions and 105 deletions.
4 changes: 2 additions & 2 deletions panel/command/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ def customize_kwargs(self, args, server_kwargs):
raise ValueError("OAuth encryption key was not a valid base64 "
"string. Generate an encryption key with "
"`panel oauth-secret` and ensure you did not "
"truncate the returned string.")
"truncate the returned string.") from None
if len(key) != 32:
raise ValueError(
"OAuth encryption key must be 32 url-safe "
Expand All @@ -605,7 +605,7 @@ def customize_kwargs(self, args, server_kwargs):
"Using OAuth2 provider with Panel requires the "
"cryptography library. Install it with `pip install "
"cryptography` or `conda install cryptography`."
)
) from None
state.encryption = Fernet(config.oauth_encryption_key)

kwargs['auth_provider'] = OAuthProvider(
Expand Down
2 changes: 1 addition & 1 deletion panel/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def write_bundled_files(name, files, explicit_dir=None, ext=None):
except Exception as e:
raise ConnectionError(
f"Failed to fetch {name} dependency: {bundle_file}. Errored with {e}."
)
) from e
try:
map_file = f'{bundle_file}.map'
map_response = requests.get(map_file)
Expand Down
4 changes: 2 additions & 2 deletions panel/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -911,9 +911,9 @@ def _apply_signatures(self):
parameters = sig_params[:-1]

processed_kws, keyword_groups = set(), []
for cls in reversed(cls.mro()):
for scls in reversed(cls.mro()):
keyword_group = []
for (k, v) in sorted(cls.__dict__.items()):
for (k, v) in sorted(scls.__dict__.items()):
if (isinstance(v, param.Parameter) and k not in processed_kws
and not v.readonly):
keyword_group.append(k)
Expand Down
4 changes: 2 additions & 2 deletions panel/io/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,14 +192,14 @@ def _generate_hash_inner(obj):
raise ValueError(
f'User hash function {hash_func!r} failed for input '
f'{obj!r} with following error: {type(e).__name__}("{e}").'
)
) from e
return output
if hasattr(obj, '__reduce__'):
h = hashlib.new("md5")
try:
reduce_data = obj.__reduce__()
except BaseException:
raise ValueError(f'Could not hash object of type {type(obj).__name__}')
raise ValueError(f'Could not hash object of type {type(obj).__name__}') from None
for item in reduce_data:
h.update(_generate_hash(item))
return h.digest()
Expand Down
2 changes: 1 addition & 1 deletion panel/io/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def script_to_html(
except Exception as e:
raise ValueError(
f'Requirements parser raised following error: {e}'
)
) from e

# Environment
if panel_version == 'local':
Expand Down
8 changes: 4 additions & 4 deletions panel/io/jupyter_server_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,9 @@ async def _get_info(self, msg_id, timeout=KERNEL_TIMEOUT):
raise TimeoutError('Timed out while waiting for kernel to open Comm channel to Panel application.')
try:
msg = await ensure_async(self.kernel.iopub_channel.get_msg(timeout=None))
except Empty:
except Empty as e:
if not await ensure_async(self.kernel.is_alive()):
raise RuntimeError("Kernel died before establishing Comm connection to Panel application.")
raise RuntimeError("Kernel died before establishing Comm connection to Panel application.") from e
continue
if msg['parent_header'].get('msg_id') != msg_id:
continue
Expand Down Expand Up @@ -381,9 +381,9 @@ async def _check_for_message(self):
break
try:
msg = await ensure_async(self.kernel.iopub_channel.get_msg(timeout=None))
except Empty:
except Empty as e:
if not await ensure_async(self.kernel.is_alive()):
raise RuntimeError("Kernel died before expected shutdown of Panel app.")
raise RuntimeError("Kernel died before expected shutdown of Panel app.") from e
continue

msg_type = msg['header']['msg_type']
Expand Down
2 changes: 1 addition & 1 deletion panel/io/liveness.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ async def get(self):
except Exception as e:
raise web.HTTPError(
500, f"Endpoint {endpoint!r} could not be served. Application raised error: {e}"
)
) from e
4 changes: 2 additions & 2 deletions panel/io/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ def bokeh_repr(obj: Model, depth: int = 0, ignored: Optional[Iterable[str]] = No
props_repr = ', '.join(props)
if isinstance(obj, FlexBox):
r += '{cls}(children=[\n'.format(cls=cls)
for obj in obj.children: # type: ignore
r += textwrap.indent(bokeh_repr(obj, depth=depth+1) + ',\n', ' ')
for child_obj in obj.children: # type: ignore
r += textwrap.indent(bokeh_repr(child_obj, depth=depth+1) + ',\n', ' ')
r += '], %s)' % props_repr
else:
r += '{cls}({props})'.format(cls=cls, props=props_repr)
Expand Down
2 changes: 1 addition & 1 deletion panel/io/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def param_rest_provider(files, endpoint):
try:
import nbconvert # noqa
except ImportError:
raise ImportError("Please install nbconvert to serve Jupyter Notebooks.")
raise ImportError("Please install nbconvert to serve Jupyter Notebooks.") from None
from nbconvert import ScriptExporter
exporter = ScriptExporter()
source, _ = exporter.from_filename(filename)
Expand Down
8 changes: 4 additions & 4 deletions panel/io/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,11 +704,11 @@ def parse_url_path(self, path: str) -> str:
try:
module = importlib.import_module(mod)
except ModuleNotFoundError:
raise HTTPError(404, 'Module not found')
raise HTTPError(404, 'Module not found') from None
try:
component = getattr(module, cls)
except AttributeError:
raise HTTPError(404, 'Component not found')
raise HTTPError(404, 'Component not found') from None

# May only access resources listed in specific attributes
if rtype not in self._resource_attrs:
Expand All @@ -717,7 +717,7 @@ def parse_url_path(self, path: str) -> str:
try:
resources = getattr(component, rtype)
except AttributeError:
raise HTTPError(404, 'Resource type not found')
raise HTTPError(404, 'Resource type not found') from None

# Handle template resources
if rtype == '_resources':
Expand Down Expand Up @@ -1174,7 +1174,7 @@ def get_server(
raise KeyError(
"Keys of the title dictionary and of the apps "
f"dictionary must match. No {slug} key found in the "
"title dictionary.")
"title dictionary.") from None
else:
title_ = title
slug = slug if slug.startswith('/') else '/'+slug
Expand Down
11 changes: 6 additions & 5 deletions panel/io/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ class _state(param.Parameterized):

def __repr__(self) -> str:
server_info = []
for server, panel, docs in self._servers.values():
for server, panel, _docs in self._servers.values():
server_info.append(
"{}:{:d} - {!r}".format(server.address or "localhost", server.port, panel)
)
Expand Down Expand Up @@ -967,10 +967,11 @@ def curdoc(self) -> Document | None:
pyodide_session = self._is_pyodide and 'pyodide_kernel' not in sys.modules
if doc and (doc.session_context or pyodide_session):
return doc
finally:
curdoc = self._curdoc.get()
if curdoc:
return curdoc
except Exception:
pass
curdoc = self._curdoc.get()
if curdoc:
return curdoc

@curdoc.setter
def curdoc(self, doc: Document) -> None:
Expand Down
2 changes: 1 addition & 1 deletion panel/layout/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ def _yoffset(self):
@property
def _object_grid(self):
grid = np.full((self.nrows, self.ncols), None, dtype=object)
for i, ((y0, x0, y1, x1), obj) in enumerate(self.objects.items()):
for (y0, x0, y1, x1), obj in self.objects.items():
l = 0 if x0 is None else x0
r = self.ncols if x1 is None else x1
t = 0 if y0 is None else y0
Expand Down
2 changes: 1 addition & 1 deletion panel/layout/gridstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def _update_sizing(self):
else:
height = 0

for i, ((y0, x0, y1, x1), obj) in enumerate(self.objects.items()):
for (y0, x0, y1, x1), obj in self.objects.items():
x0 = 0 if x0 is None else x0
x1 = (self.ncols) if x1 is None else x1
y0 = 0 if y0 is None else y0
Expand Down
10 changes: 5 additions & 5 deletions panel/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,18 +578,18 @@ def _get_triggers(
def _get_specs(
self, link: 'Link', source: 'Reactive', target: 'JSLinkTarget'
) -> Sequence[Tuple['SourceModelSpec', 'TargetModelSpec', str | None]]:
for src_spec, code in link.code.items():
src_specs = src_spec.split('.')
if src_spec.startswith('event:'):
src_spec = (None, src_spec)
for spec in link.code:
src_specs = spec.split('.')
if spec.startswith('event:'):
src_spec = (None, spec)
elif len(src_specs) > 1:
src_spec = ('.'.join(src_specs[:-1]), src_specs[-1])
else:
src_prop = src_specs[0]
if isinstance(source, Reactive):
src_prop = source._rename.get(src_prop, src_prop)
src_spec = (None, src_prop)
return [(src_spec, (None, None), code)]
return [(src_spec, (None, None), link.code[spec])]



Expand Down
43 changes: 21 additions & 22 deletions panel/pane/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,47 +267,46 @@ def _update_object(
]
if indexes:
index = indexes[0]
new_model = (new_model,) + parent.children[index][1:]
parent.children[index] = new_model
else:
raise ValueError
new_model = (new_model,) + parent.children[index][1:]
elif isinstance(parent, _BkReactiveHTML):
for node, children in parent.children.items():
if old_model in children:
index = children.index(old_model)
new_models = list(children)
new_models[index] = new_model
parent.children[node] = new_models
break
elif isinstance(parent, _BkTabs):
index = [tab.child for tab in parent.tabs].index(old_model)
old_tab = parent.tabs[index]
props = dict(old_tab.properties_with_values(), child=new_model)
parent.tabs[index] = _BkTabPanel(**props)
else:
index = parent.children.index(old_model)
parent.children[index] = new_model
except ValueError:
self.param.warning(
f'{type(self).__name__} pane model {old_model!r} could not be '
f'replaced with new model {new_model!r}, ensure that the parent '
'is not modified at the same time the panel is being updated.'
)
else:
if isinstance(parent, _BkReactiveHTML):
parent.children[node] = new_models
elif isinstance(parent, _BkTabs):
old_tab = parent.tabs[index]
props = dict(old_tab.properties_with_values(), child=new_model)
parent.tabs[index] = _BkTabPanel(**props)
else:
parent.children[index] = new_model
layout_parent = self.layout._models.get(ref, [None])[0]
if parent is layout_parent:
parent.update(**self.layout._compute_sizing_mode(
parent.children,
dict(
sizing_mode=self.layout.sizing_mode,
styles=self.layout.styles,
width=self.layout.width,
min_width=self.layout.min_width,
margin=self.layout.margin
)
))
return

layout_parent = self.layout._models.get(ref, [None])[0]
if parent is layout_parent:
parent.update(**self.layout._compute_sizing_mode(
parent.children,
dict(
sizing_mode=self.layout.sizing_mode,
styles=self.layout.styles,
width=self.layout.width,
min_width=self.layout.min_width,
margin=self.layout.margin
)
))

from ..io import state
ref = root.ref['id']
Expand Down
4 changes: 2 additions & 2 deletions panel/pane/holoviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ def _render(self, doc, comm, root):
params = {}
if self.theme is not None:
params['theme'] = self.theme
elif doc.theme and getattr(doc.theme, '_json') != {'attrs': {}}:
elif doc.theme and doc.theme._json != {'attrs': {}}:
params['theme'] = doc.theme
elif self._design.theme.bokeh_theme:
params['theme'] = self._design.theme.bokeh_theme
Expand Down Expand Up @@ -897,7 +897,7 @@ def link_axes(root_view, root_model):
changed.append('y_range')

# Reinitialize callbacks linked to replaced axes
subplots = getattr(p, 'subplots')
subplots = p.subplots
if subplots:
plots = subplots.values()
else:
Expand Down
4 changes: 2 additions & 2 deletions panel/pane/vtk/vtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class AbstractVTK(PaneBase):
def _process_param_change(self, msg):
msg = super()._process_param_change(msg)
if 'axes' in msg and msg['axes'] is not None:
VTKAxes = getattr(sys.modules['panel.models.vtk'], 'VTKAxes')
VTKAxes = sys.modules['panel.models.vtk'].VTKAxes
axes = msg['axes']
msg['axes'] = VTKAxes(**axes)
return msg
Expand All @@ -86,7 +86,7 @@ def _update_model(
root: Model, model: Model, doc: Document, comm: Optional[Comm]
) -> None:
if 'axes' in msg and msg['axes'] is not None:
VTKAxes = getattr(sys.modules['panel.models.vtk'], 'VTKAxes')
VTKAxes = sys.modules['panel.models.vtk'].VTKAxes
axes = msg['axes']
if isinstance(axes, dict):
msg['axes'] = VTKAxes(**axes)
Expand Down
10 changes: 5 additions & 5 deletions panel/param.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,11 +372,11 @@ def toggle_pane(change, parameter=pname):
pane = Param(parameterized, name=parameterized.name,
**kwargs)
if isinstance(self._expand_layout, Tabs):
title = self.object.param[pname].label
title = self.object.param[parameter].label
pane = (title, pane)
self._expand_layout.append(pane)

def update_pane(change, parameter=pname):
def update_pane(change, parameter=pname, toggle=toggle):
"Adds or removes subpanel from layout"
layout = self._expand_layout
existing = [p for p in layout.objects if isinstance(p, Param)
Expand Down Expand Up @@ -924,10 +924,10 @@ def update_pane(*events):
deps.append(p)
self._replace_pane()

for _, params in full_groupby(params, lambda x: (x.inst or x.cls, x.what)):
p = params[0]
for _, sub_params in full_groupby(params, lambda x: (x.inst or x.cls, x.what)):
p = sub_params[0]
pobj = (p.inst or p.cls)
ps = [_p.name for _p in params]
ps = [_p.name for _p in sub_params]
if isinstance(pobj, Reactive) and self.loading_indicator:
props = {p: 'loading' for p in ps if p in pobj._linkable_params}
if props:
Expand Down
2 changes: 1 addition & 1 deletion panel/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def __init__(self, stages=[], graph={}, **params):
try:
import holoviews as hv
except Exception:
raise ImportError('Pipeline requires holoviews to be installed')
raise ImportError('Pipeline requires holoviews to be installed') from None

super().__init__(**params)

Expand Down
Loading

0 comments on commit 5b5dda6

Please sign in to comment.