Skip to content

Commit

Permalink
Update pre-commit (#6867)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxbro authored May 27, 2024
1 parent 0f7d191 commit 97c2918
Show file tree
Hide file tree
Showing 38 changed files with 98 additions and 107 deletions.
12 changes: 6 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
default_stages: [commit]
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v4.6.0
hooks:
- id: check-builtin-literals
- id: check-case-conflict
Expand All @@ -17,7 +17,7 @@ repos:
exclude: \.min\.js$
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.9
rev: v0.4.5
hooks:
- id: ruff
files: panel/
Expand All @@ -33,13 +33,13 @@ repos:
args: [-i, tags]
exclude: '^lite/files/.*/'
- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
rev: v2.3.0
hooks:
- id: codespell
additional_dependencies:
- tomli
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
- repo: https://github.com/hoxbro/prettier-pre-commit
rev: v3.2.5
hooks:
- id: prettier
entry: prettier --write --ignore-unknown --no-error-on-unmatched-pattern
Expand All @@ -50,7 +50,7 @@ repos:
- id: oxipng
stages: [manual]
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.56.0
rev: v9.3.0
hooks:
- id: eslint
args: ['-c', 'panel/.eslintrc.js', 'panel/*.ts', 'panel/models/**/*.ts']
Expand Down
2 changes: 1 addition & 1 deletion CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ If you are a leading community member: **Please act as a role model**.
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
identity and expression, level of experience, education, socioeconomic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.

Expand Down
2 changes: 1 addition & 1 deletion examples/reference/widgets/ToggleGroup.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
"source": [
"### Controls\n",
"\n",
"The `ToggleGroup` widget (concretly the created, underlying widget) exposes a number of options which can be changed from both Python and Javascript. Try out the effect of these parameters interactively:"
"The `ToggleGroup` widget (concretely the created, underlying widget) exposes a number of options which can be changed from both Python and Javascript. Try out the effect of these parameters interactively:"
]
},
{
Expand Down
2 changes: 1 addition & 1 deletion panel/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def main(args=None):

if len(sys.argv) == 1:
all_commands = sorted([c.name for c in bokeh_commands])
die("ERROR: Must specify subcommand, one of: %s" % nice_join(all_commands))
die(f"ERROR: Must specify subcommand, one of: {nice_join(all_commands)}")

if sys.argv[1] in ('--help', '-h'):
args = parser.parse_args(sys.argv[1:])
Expand Down
4 changes: 2 additions & 2 deletions panel/command/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ def customize_kwargs(self, args, server_kwargs):
pattern = REST_PROVIDERS[args.rest_provider](files, args.rest_endpoint)
patterns.extend(pattern)
elif args.rest_provider is not None:
raise ValueError("rest-provider %r not recognized." % args.rest_provider)
raise ValueError(f"rest-provider {args.rest_provider!r} not recognized.")

config.autoreload = args.autoreload
config.global_loading_spinner = args.global_loading_spinner
Expand Down Expand Up @@ -379,7 +379,7 @@ def customize_kwargs(self, args, server_kwargs):
if args.liveness:
argvs = {f: args.args for f in files}
applications = build_single_handler_applications(files, argvs)
patterns += [(r"/%s" % args.liveness_endpoint, LivenessHandler, dict(applications=applications))]
patterns += [(rf"/{args.liveness_endpoint}", LivenessHandler, dict(applications=applications))]

config.profiler = args.profiler
if args.admin:
Expand Down
4 changes: 2 additions & 2 deletions panel/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,8 +746,8 @@ def __call__(self, *args, **params):
state._extensions.append(arg)
ReactiveHTMLMetaclass._loaded_extensions.add(arg)
else:
self.param.warning('%s extension not recognized and '
'will be skipped.' % arg)
self.param.warning(f'{arg} extension not recognized and '
'will be skipped.')

for k, v in params.items():
if k == 'design' and isinstance(v, str):
Expand Down
2 changes: 1 addition & 1 deletion panel/interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def __init__(self, object, params={}, **kwargs):
self._inner_layout = Row(self._pane)
widgets = [widget for _, widget in widgets if isinstance(widget, Widget)]
if 'name' in params:
widgets.insert(0, HTML('<h2>%s</h2>' % self.name))
widgets.insert(0, HTML(f'<h2>{self.name}</h2>'))
self.widget_box = Column(*widgets)
self.layout.objects = [self.widget_box, self._inner_layout]
self._link_widgets()
Expand Down
2 changes: 1 addition & 1 deletion panel/io/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def update_cds(new, nb=False):
else:
msg = new.getMessage()
line_color = 'black'
if msg.startswith('Session %s logged' % sid):
if msg.startswith(f'Session {sid} logged'):
etype = 'logging'
line_color = EVENT_TYPES.get(etype)
elif msg.startswith(LOG_SESSION_DESTROYED % sid):
Expand Down
4 changes: 2 additions & 2 deletions panel/io/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def bokeh_repr(obj: Model, depth: int = 0, ignored: Optional[Iterable[str]] = No
if k in ignored:
continue
if isinstance(v, Model):
v = '%s()' % type(v).__name__
v = f'{type(v).__name__}()'
else:
v = repr(v)
if len(v) > 30:
Expand All @@ -168,7 +168,7 @@ def bokeh_repr(obj: Model, depth: int = 0, ignored: Optional[Iterable[str]] = No
r += f'{cls}(children=[\n'
for child_obj in obj.children: # type: ignore
r += textwrap.indent(bokeh_repr(child_obj, depth=depth+1) + ',\n', ' ')
r += '], %s)' % props_repr
r += f'], {props_repr})'
else:
r += f'{cls}({props_repr})'
return r
Expand Down
4 changes: 2 additions & 2 deletions panel/io/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def tranquilizer_rest_provider(files, endpoint):
"""
app = build_tranquilize_application(files)
tr = WSGIContainer(app)
return [(r"^/%s/.*" % endpoint, web.FallbackHandler, dict(fallback=tr))]
return [(rf"^/{endpoint}/.*", web.FallbackHandler, dict(fallback=tr))]


def param_rest_provider(files, endpoint):
Expand Down Expand Up @@ -169,7 +169,7 @@ def param_rest_provider(files, endpoint):

if endpoint and not endpoint.endswith('/'):
endpoint += '/'
return [((r"^/%s.*" % endpoint if endpoint else r"^.*"), ParamHandler, dict(root=endpoint))]
return [((rf"^/{endpoint}.*" if endpoint else r"^.*"), ParamHandler, dict(root=endpoint))]


REST_PROVIDERS = {
Expand Down
4 changes: 2 additions & 2 deletions panel/io/save.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,8 @@ def save(
resources = INLINE
mode = 'inline'
else:
raise ValueError("Resources %r not recognized, specify one "
"of 'CDN' or 'INLINE'." % resources)
raise ValueError(f"Resources {resources!r} not recognized, specify one "
"of 'CDN' or 'INLINE'.")
elif isinstance(resources, BkResources):
mode = resources.mode

Expand Down
6 changes: 3 additions & 3 deletions panel/io/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -857,9 +857,9 @@ def get_static_routes(static_dirs):
"this is reserved for internal use.")
path = fullpath(path)
if not os.path.isdir(path):
raise ValueError("Cannot serve non-existent path %s" % path)
raise ValueError(f"Cannot serve non-existent path {path}")
patterns.append(
(r"%s/(.*)" % slug, StaticFileHandler, {"path": path})
(rf"{slug}/(.*)", StaticFileHandler, {"path": path})
)
patterns.append((
f'/{COMPONENT_PATH}(.*)', ComponentResourceHandler, {}
Expand Down Expand Up @@ -1085,7 +1085,7 @@ def get_server(

if liveness:
liveness_endpoint = 'liveness' if isinstance(liveness, bool) else liveness
extra_patterns += [(r"/%s" % liveness_endpoint, LivenessHandler, dict(applications=apps))]
extra_patterns += [(rf"/{liveness_endpoint}", LivenessHandler, dict(applications=apps))]

opts = dict(kwargs)
if loop:
Expand Down
15 changes: 7 additions & 8 deletions panel/layout/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def __repr__(self, depth: int = 0, max_depth: int = 10) -> str:
template = '{cls}({params}){spacer}{objs}'
return template.format(
cls=cls, params=', '.join(params),
objs=('%s' % spacer).join(objs), spacer=spacer)
objs=str(spacer).join(objs), spacer=spacer)

#----------------------------------------------------------------
# Callback API
Expand Down Expand Up @@ -435,9 +435,8 @@ def clone(self, *objects: Any, **params: Any) -> 'ListLike':
else:
objects = self.objects
elif 'objects' in params:
raise ValueError("A %s's objects should be supplied either "
"as arguments or as a keyword, not both."
% type(self).__name__)
raise ValueError(f"A {type(self).__name__}'s objects should be supplied either "
"as arguments or as a keyword, not both.")
p = dict(self.param.values(), **params)
del p['objects']
return type(self)(*objects, **p)
Expand Down Expand Up @@ -552,9 +551,9 @@ class NamedListLike(param.Parameterized):
def __init__(self, *items: list[Any | tuple[str, Any]], **params: Any):
if 'objects' in params:
if items:
raise ValueError('%s objects should be supplied either '
raise ValueError(f'{type(self).__name__} objects should be supplied either '
'as positional arguments or as a keyword, '
'not both.' % type(self).__name__)
'not both.')
items = params.pop('objects')
params['objects'], self._names = self._to_objects_and_names(items)
super().__init__(**params)
Expand Down Expand Up @@ -814,9 +813,9 @@ def __init__(self, *objects: Any, **params: Any):
from ..pane import panel
if objects:
if 'objects' in params:
raise ValueError("A %s's objects should be supplied either "
raise ValueError(f"A {type(self).__name__}'s objects should be supplied either "
"as positional arguments or as a keyword, "
"not both." % type(self).__name__)
"not both.")
params['objects'] = [panel(pane) for pane in objects]
elif 'objects' in params:
objects = params['objects']
Expand Down
4 changes: 2 additions & 2 deletions panel/layout/flex.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ def __init__(self, *objects, **params):
params['sizing_mode'] = 'stretch_height'
if objects:
if 'objects' in params:
raise ValueError("A %s's objects should be supplied either "
raise ValueError(f"A {type(self).__name__}'s objects should be supplied either "
"as positional arguments or as a keyword, "
"not both." % type(self).__name__)
"not both.")
params['objects'] = [panel(pane) for pane in objects]
elif 'objects' in params:
objects = params['objects']
Expand Down
9 changes: 4 additions & 5 deletions panel/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def assert_target_syncable(
elif p not in target.param and p not in list(target._rename.values()):
matches = difflib.get_close_matches(p, list(target.param))
if matches:
matches_repr = ' Similar parameters include: %r' % matches
matches_repr = f' Similar parameters include: {matches!r}'
else:
matches_repr = ''
raise ValueError(
Expand Down Expand Up @@ -146,7 +146,7 @@ def __init__(
a JS code snippet to execute.
"""
if source is None:
raise ValueError('%s must define a source' % type(self).__name__)
raise ValueError(f'{type(self).__name__} must define a source')
# Source is stored as a weakref to allow it to be garbage collected
self._source = None if source is None else weakref.ref(source)
if not args:
Expand Down Expand Up @@ -289,7 +289,7 @@ class Link(Callback):

def __init__(self, source: 'Reactive', target: Optional['JSLinkTarget'] = None, **params):
if self._requires_target and target is None:
raise ValueError('%s must define a target.' % type(self).__name__)
raise ValueError(f'{type(self).__name__} must define a target.')
# Source is stored as a weakref to allow it to be garbage collected
self._target = None if target is None else weakref.ref(target)
super().__init__(source, **params)
Expand Down Expand Up @@ -709,8 +709,7 @@ def _initialize_models(
setattr(tgt_model, tgt_spec, value)
if tgt_model is None and not link.code:
raise ValueError('Model could not be resolved on target '
'%s and no custom code was specified.' %
type(self.target).__name__)
f'{type(self.target).__name__} and no custom code was specified.')

def _process_references(self, references: dict[str, str]) -> None:
"""
Expand Down
10 changes: 5 additions & 5 deletions panel/models/reactive_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,17 @@ def handle_data(self, data):
if match[2:-1] not in self.loop_var_map[var]:
self.loop_var_map[var].append(match[2:-1])
if var.endswith('.index0'):
matches.append('${%s }}]}' % var)
matches.append('${%s }}]}' % var) # noqa: UP031
else:
matches.append('${%s}' % var)
matches.append('${%s}' % var) # noqa: UP031

literal_matches = []
for match in self._literal_re.findall(data):
match = match[2:-2].strip()
if match.endswith('.index0'):
literal_matches.append('{{%s }}]}' % match)
literal_matches.append('{{%s }}]}' % match) # noqa: UP031
else:
literal_matches.append('{{ %s }}' % match)
literal_matches.append('{{ %s }}' % match) # noqa: UP031

# Detect templating for loops
list_loop = re.findall(list_iter_re, data)
Expand Down Expand Up @@ -175,7 +175,7 @@ def handle_data(self, data):
if match and (match.strip() in self.loop_map or '[' in match) and self._open_for:
if match.strip() in self.loop_map:
loop_match = self.loop_map[match.strip()]
matches[matches.index('${%s}' % match)] = '${%s}' % loop_match
matches[matches.index(f'${{{match}}}')] = f'${{{loop_match}}}'
match = loop_match
elif '[' in match:
match, _ = match.split('[')
Expand Down
6 changes: 3 additions & 3 deletions panel/pane/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,8 +454,8 @@ def get_pane_type(cls, obj: Any, **kwargs) -> type['PaneBase']:
raise ValueError('If a Pane declares no priority '
'the applies method should return a '
'priority value specific to the '
'object type or False, but the %s pane '
'declares no priority.' % p.__name__)
f'object type or False, but the {p.__name__} pane '
'declares no priority.')
elif priority is None or priority is False:
continue
descendents.append((priority, applies, p))
Expand All @@ -469,7 +469,7 @@ def get_pane_type(cls, obj: Any, **kwargs) -> type['PaneBase']:
if not applies:
continue
return pane_type
raise TypeError('%s type could not be rendered.' % type(obj).__name__)
raise TypeError(f'{type(obj).__name__} type could not be rendered.')


class ModelPane(PaneBase):
Expand Down
2 changes: 1 addition & 1 deletion panel/pane/holoviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ def widgets_from_dimensions(cls, object, widget_types=None, widgets_type='indivi
object = object.hmap

if isinstance(object, DynamicMap) and object.unbounded:
dims = ', '.join('%r' % dim for dim in object.unbounded)
dims = ', '.join(f'{dim!r}' for dim in object.unbounded)
msg = ('DynamicMap cannot be displayed without explicit indexing '
'as {dims} dimension(s) are unbounded. '
'\nSet dimensions bounds with the DynamicMap redim.range '
Expand Down
4 changes: 2 additions & 2 deletions panel/pane/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,8 +425,8 @@ def applies(cls, obj: Any) -> float | bool | None:

def _type_error(self, object):
if isinstance(object, str):
raise ValueError("%s pane cannot parse string that is not a filename, "
"URL or a SVG XML contents." % type(self).__name__)
raise ValueError(f"{type(self).__name__} pane cannot parse string that is not a filename, "
"URL or a SVG XML contents.")
super()._type_error(object)

def _data(self, obj):
Expand Down
2 changes: 1 addition & 1 deletion panel/pane/vtk/synchronizable_deserializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def capitalize(name):
def fill_array(vtk_arr, state, zf):
vtk_arr.SetNumberOfComponents(state['numberOfComponents'])
vtk_arr.SetNumberOfTuples(state['size']//state['numberOfComponents'])
data = zf.read('data/%s' % state['hash'])
data = zf.read('data/{}'.format(state['hash']))
dataType = arrayTypesMapping[vtk_arr.GetDataType()]
elementSize = struct.calcsize(dataType)
if vtk_arr.GetDataType() == 12:
Expand Down
9 changes: 4 additions & 5 deletions panel/pane/vtk/synchronizable_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def getJSArrayType(dataArray):
def zipCompression(name, data):
with io.BytesIO() as in_memory:
with zipfile.ZipFile(in_memory, mode="w") as zf:
zf.writestr('data/%s' % name,
zf.writestr(f'data/{name}',
data, zipfile.ZIP_DEFLATED)
in_memory.seek(0)
return in_memory.read()
Expand Down Expand Up @@ -393,7 +393,7 @@ def pad(depth):


def wrapId(idStr):
return 'instance:${%s}' % idStr
return f'instance:${{{idStr}}}'

# -----------------------------------------------------------------------------

Expand Down Expand Up @@ -570,7 +570,7 @@ def extractRequiredFields(extractedFields, parent, dataset, context, requestedFi

def annotationSerializer(parent, prop, propId, context, depth):
if context.debugSerializers:
print('%s!!!Annotations are not handled directly by vtk.js but by bokeh model' % pad(depth))
print(f'{pad(depth)}!!!Annotations are not handled directly by vtk.js but by bokeh model')

context.addAnnotation(parent, prop, propId)

Expand Down Expand Up @@ -1243,8 +1243,7 @@ def rendererSerializer(parent, instance, objId, context, depth):
dependencies.append(viewPropInstance)
viewPropIds.append(viewPropId)

calls += context.buildDependencyCallList('%s-props' %
objId, viewPropIds, 'addViewProp', 'removeViewProp')
calls += context.buildDependencyCallList(f'{objId}-props', viewPropIds, 'addViewProp', 'removeViewProp')

return {
'parent': context.getReferenceId(parent),
Expand Down
Loading

0 comments on commit 97c2918

Please sign in to comment.