Skip to content

Commit

Permalink
More lint cleanup (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Dec 27, 2022
1 parent 40c7c35 commit b9ecbf5
Show file tree
Hide file tree
Showing 8 changed files with 38 additions and 32 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ repos:
- id: mdformat

- repo: https://github.com/psf/black
rev: 22.10.0
rev: 22.12.0
hooks:
- id: black

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.189
rev: v0.0.194
hooks:
- id: ruff
args: ["--fix"]
13 changes: 9 additions & 4 deletions jupyter_events/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ def add_modifier(
"""
# Ensure that this is a callable function/method
if not callable(modifier):
raise TypeError("`modifier` must be a callable")
msg = "`modifier` must be a callable"
raise TypeError(msg)

# Now let's verify the function signature.
signature = inspect.signature(modifier)
Expand All @@ -211,13 +212,14 @@ def modifier_signature( # type:ignore[empty-body]
if schema_id is None or id == schema_id:
self._modifiers[id].add(modifier)
else:
raise ModifierError(
msg = (
"Modifiers are required to follow an exact function/method "
"signature. The signature should look like:"
f"\n\n\tdef my_modifier{expected_signature}:\n\n"
"Check that you are using type annotations for each argument "
"and the return value."
)
raise ModifierError(msg)

def remove_modifier(
self, *, schema_id: Optional[str] = None, modifier: Callable[[str, dict], dict]
Expand Down Expand Up @@ -262,7 +264,8 @@ def add_listener(
A callable function/method that executes when the named event occurs.
"""
if not callable(listener):
raise TypeError("`listener` must be a callable")
msg = "`listener` must be a callable"
raise TypeError(msg)

signature = inspect.signature(listener)

Expand All @@ -287,14 +290,16 @@ async def listener_signature(logger: EventLogger, schema_id: str, data: dict) ->
else:
self._unmodified_listeners[schema_id].add(listener)
else:
raise ListenerError(
msg = (
"Listeners are required to follow an exact function/method "
"signature. The signature should look like:"
f"\n\n\tasync def my_listener{expected_signature}:\n\n"
"Check that you are using type annotations for each argument "
"and the return value."
)

raise ListenerError(msg)

def remove_listener(
self,
*,
Expand Down
8 changes: 4 additions & 4 deletions jupyter_events/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def _load_schema(schema: Union[dict, str, PurePath]) -> dict:
# if schema is PurePath, ensure file exists at path and then load from file
if isinstance(schema, PurePath):
if not Path(schema).exists():
raise EventSchemaFileAbsent(f'Schema file not present at path "{schema}".')
msg = f'Schema file not present at path "{schema}".'
raise EventSchemaFileAbsent(msg)

loaded_schema = yaml.load(schema)
EventSchema._ensure_yaml_loaded(loaded_schema)
Expand All @@ -121,9 +122,8 @@ def _load_schema(schema: Union[dict, str, PurePath]) -> dict:
EventSchema._ensure_yaml_loaded(loaded_schema, was_str=True)
return loaded_schema

raise EventSchemaUnrecognized(
f"Expected a dictionary, string, or PurePath, but instead received {schema.__class__.__name__}."
)
msg = f"Expected a dictionary, string, or PurePath, but instead received {schema.__class__.__name__}."
raise EventSchemaUnrecognized(msg)

@property
def id(self) -> str:
Expand Down
19 changes: 11 additions & 8 deletions jupyter_events/schema_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from .schema import EventSchema


class SchemaRegistryException(Exception): # noqa
class SchemaRegistryException(Exception): # noqa[N818]
"""Exception class for Jupyter Events Schema Registry Errors."""


Expand All @@ -25,10 +25,11 @@ def __repr__(self) -> str:

def _add(self, schema_obj: EventSchema):
if schema_obj.id in self._schemas:
raise SchemaRegistryException(
msg = (
f"The schema, {schema_obj.id}, is already "
"registered. Try removing it and registering it again."
)
raise SchemaRegistryException(msg)
self._schemas[schema_obj.id] = schema_obj

@property
Expand All @@ -52,23 +53,25 @@ def get(self, id: str) -> EventSchema:
"""
try:
return self._schemas[id]
except KeyError as e:
raise KeyError(
except KeyError:
msg = (
f"The requested schema, {id}, was not found in the "
"schema registry. Are you sure it was previously registered?"
) from e
)
raise KeyError(msg) from None

def remove(self, id: str) -> None:
"""Remove a given schema. If the schema is not found,
this will raise a KeyError.
"""
try:
del self._schemas[id]
except KeyError as e:
raise KeyError(
except KeyError:
msg = (
f"The requested schema, {id}, was not found in the "
"schema registry. Are you sure it was previously registered?"
) from e
)
raise KeyError(msg) from None

def validate_event(self, id: str, data: dict) -> None:
"""Validate an event against a schema within this
Expand Down
6 changes: 2 additions & 4 deletions jupyter_events/traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,8 @@ def validate_elements(self, obj, value):

def element_error(self, obj):
"""Raise an error for bad elements."""
raise TraitError(
"Elements in the '{}' trait of an {} instance "
"must be Python `logging` handler instances.".format(self.name, obj.__class__.__name__)
)
msg = f"Elements in the '{self.name}' trait of an {obj.__class__.__name__} instance must be Python `logging` handler instances."
raise TraitError(msg)

def validate(self, obj, value):
"""Validate an object."""
Expand Down
5 changes: 3 additions & 2 deletions jupyter_events/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,10 @@ def validate_schema(schema: dict):
if reserved_property_msg in str(err):
idx = str(err).find(reserved_property_msg)
bad_property = str(err)[:idx].strip()
raise ValidationError(
msg = (
f"{bad_property} is an invalid property name because it "
"starts with `__`. Properties starting with 'dunder' "
"are reserved as special meta-fields for Jupyter Events to use."
) from err
)
raise ValidationError(msg) from err
raise err
11 changes: 5 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ cli = [
"click",
"rich"
]
lint = ["black[jupyter]==22.10.0", "mdformat>0.7", "ruff==0.0.189"]
typing = ["mypy>=0.990"]

[tool.hatch.version]
path = "jupyter_events/_version.py"
Expand All @@ -84,17 +82,18 @@ nowarn = "test -W default {args}"
features = ["test"]
dependencies = ["coverage", "pytest-cov"]
[tool.hatch.envs.cov.scripts]
test = "python -m pytest -vv --cov jupyter_events --cov-branch --cov-report term-missing:skip-covered --cov-fail-under 85 {args}"
test = "python -m pytest -vv --cov jupyter_events --cov-branch --cov-report term-missing:skip-covered --cov-fail-under 80 {args}"
nowarn = "test -W default {args}"

[tool.hatch.envs.typing]
features = ["test", "typing"]
features = ["test"]
dependencies = ["mypy>=0.990"]
[tool.hatch.envs.typing.scripts]
test = "mypy --install-types --non-interactive {args:.}"

[tool.hatch.envs.lint]
features = ["lint"]
dependencies = ["black[jupyter]==22.12.0", "mdformat>0.7", "ruff==0.0.194"]
detached = true
[tool.hatch.envs.lint.scripts]
style = [
"ruff {args:.}",
Expand Down Expand Up @@ -138,7 +137,7 @@ target-version = ["py37"]
target-version = "py37"
line-length = 100
select = [
"A", "B", "C", "E", "F", "FBT", "I", "N", "Q", "RUF", "S", "T",
"A", "B", "C", "E", "EM", "F", "FBT", "I", "N", "Q", "RUF", "S", "T",
"UP", "W", "YTT",
]
ignore = [
Expand Down
4 changes: 2 additions & 2 deletions tests/test_listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async def test_listener_that_raises_exception(jp_event_logger, schema):
app_log.addHandler(h)

async def listener_raise_exception(logger: EventLogger, schema_id: str, data: dict) -> None:
raise Exception("This failed")
raise Exception("This failed") # noqa

event_logger.add_listener(schema_id=schema.id, listener=listener_raise_exception)
event_logger.emit(schema_id=schema.id, data={"prop": "hello, world"})
Expand Down Expand Up @@ -118,7 +118,7 @@ async def test_bad_listener_does_not_break_good_listener(jp_event_logger, schema
listener_was_called = False

async def listener_raise_exception(logger: EventLogger, schema_id: str, data: dict) -> None:
raise Exception("This failed")
raise Exception("This failed") # noqa

async def my_listener(logger: EventLogger, schema_id: str, data: dict) -> None:
global listener_was_called
Expand Down

0 comments on commit b9ecbf5

Please sign in to comment.