Skip to content

Commit

Permalink
Other good-seeming recommendations from ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
fritzm committed Oct 22, 2023
1 parent 8758c26 commit 62dc263
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 35 deletions.
8 changes: 5 additions & 3 deletions src/lsst/cmservice/cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,10 @@ def delete() -> None:


def _lookahead(iterable: Iterable[T]) -> Generator[tuple[T, bool], None, None]:
"""A generator which returns all elements of the provided iteratable as
tuples with an additional `bool`; the `bool` will be `True` on the last
"""Elaborate iterable with end indication.
Returns a generator which returns all elements of the provided iteratable
as tuples with an additional `bool`; the `bool` will be `True` on the last
element and `False` otherwise.
"""
it = iter(iterable)
Expand Down Expand Up @@ -160,7 +162,7 @@ def tree(client: CMClient, path: str | None) -> None:
@main.command()
@click.option("--reset", is_flag=True, help="Delete all existing database data.")
@run_with_asyncio
async def init(reset: bool) -> None: # pragma: no cover
async def init(*, reset: bool) -> None: # pragma: no cover
"""Initialize the service database."""
logger = structlog.get_logger(config.logger_name)
engine = create_database_engine(config.database_url, config.database_password)
Expand Down
17 changes: 10 additions & 7 deletions src/lsst/cmservice/cli/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,27 @@
class EnumChoice(click.Choice):
"""A version of click.Choice specialized for enum types."""

def __init__(self, enum: type[Enum], case_sensitive: bool = True) -> None:
def __init__(self: "EnumChoice", enum: type[Enum], *, case_sensitive: bool = True) -> None:
self._enum = enum
super().__init__(list(enum.__members__.keys()), case_sensitive=case_sensitive)

def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> Enum:
def convert(
self: "EnumChoice",
value: Any,
param: click.Parameter | None,
ctx: click.Context | None,
) -> Enum:
converted_str = super().convert(value, param, ctx)
return self._enum.__members__[converted_str]


class PartialOption:
"""Wraps click.option decorator with partial arguments for convenient
reuse.
"""
"""Wrap partially specified click.option decorator for convenient reuse."""

def __init__(self, *param_decls: str, **attrs: Any) -> None:
def __init__(self: "PartialOption", *param_decls: str, **attrs: Any) -> None:
self._partial = partial(click.option, *param_decls, cls=partial(click.Option), **attrs)

def __call__(self, *param_decls: str, **attrs: Any) -> Callable[[FC], FC]:
def __call__(self: "PartialOption", *param_decls: str, **attrs: Any) -> Callable[[FC], FC]:
return self._partial(*param_decls, **attrs)


Expand Down
10 changes: 5 additions & 5 deletions src/lsst/cmservice/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
class CMClient:
"""Interface for accessing remote cm-service."""

def __init__(self, url: str) -> None:
def __init__(self: "CMClient", url: str) -> None:
self._client = httpx.Client(base_url=url)

def get_productions(self) -> list[models.Production]:
def get_productions(self: "CMClient") -> list[models.Production]:
skip = 0
productions = []
query = "productions?"
Expand All @@ -21,7 +21,7 @@ def get_productions(self) -> list[models.Production]:
skip += len(results)
return productions

def get_campaigns(self, production: int | None = None) -> list[models.Campaign]:
def get_campaigns(self: "CMClient", production: int | None = None) -> list[models.Campaign]:
skip = 0
campaigns = []
query = f"campaigns?{f'production={production}&' if production else ''}"
Expand All @@ -30,7 +30,7 @@ def get_campaigns(self, production: int | None = None) -> list[models.Campaign]:
skip += len(results)
return campaigns

def get_steps(self, campaign: int | None = None) -> list[models.Step]:
def get_steps(self: "CMClient", campaign: int | None = None) -> list[models.Step]:
skip = 0
steps = []
query = f"steps?{f'campaign={campaign}&' if campaign else ''}"
Expand All @@ -39,7 +39,7 @@ def get_steps(self, campaign: int | None = None) -> list[models.Step]:
skip += len(results)
return steps

def get_groups(self, step: int | None = None) -> list[models.Group]:
def get_groups(self: "CMClient", step: int | None = None) -> list[models.Group]:
skip = 0
groups = []
query = f"groups?{f'step={step}&' if step else ''}"
Expand Down
23 changes: 11 additions & 12 deletions src/lsst/cmservice/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ class Configuration(BaseSettings):
"""Configuration for cm-service."""

prefix: str = Field(
"/cm-service/v1",
default="/cm-service/v1",
title="The URL prefix for the cm-service API",
env="CM_URL_PREFIX",
)

database_url: str = Field(
"",
default="",
title="The URL for the cm-service database",
env="CM_DATABASE_URL",
)
Expand All @@ -27,31 +27,31 @@ class Configuration(BaseSettings):
)

database_schema: str | None = Field(
None,
default=None,
title="Schema to use for cm-service database",
env="CM_DATABASE_SCHEMA",
)

database_echo: bool | str = Field(
False,
default=False,
title="SQLAlchemy engine echo setting for the cm-service database",
env="CM_DATABASE_ECHO",
)

profile: Profile = Field(
Profile.development,
default=Profile.development,
title="Application logging profile",
env="CM_LOG_PROFILE",
)

logger_name: str = Field(
"cmservice",
default="cmservice",
title="The root name of the application's logger",
env="CM_LOGGER",
)

log_level: LogLevel = Field(
LogLevel.INFO,
default=LogLevel.INFO,
title="Log level of the application's logger",
env="CM_LOG_LEVEL",
)
Expand All @@ -61,7 +61,7 @@ class Configuration(BaseSettings):
)

arq_redis_url: RedisDsn = Field(
RedisDsn("redis://localhost:6379/1", scheme="redis"),
defuault=RedisDsn("redis://localhost:6379/1", scheme="redis"),
title="The URL for the cm-service arq redis database",
env="CM_ARQ_REDIS_URL",
)
Expand All @@ -72,16 +72,15 @@ class Configuration(BaseSettings):
)

@property
def arq_redis_settings(self) -> RedisSettings:
def arq_redis_settings(self: "Configuration") -> RedisSettings:
"""Create a Redis settings instance for arq."""
redis_settings = RedisSettings(
return RedisSettings(
host=self.arq_redis_url.host or "localhost",
port=int(self.arq_redis_url.port or 6379),
password=self.arq_redis_password,
database=int(self.arq_redis_url.path.lstrip("/")) if self.arq_redis_url.path else 0,
)
return redis_settings


config = Configuration() # pyright: ignore
config = Configuration()
"""Configuration for cm-service."""
6 changes: 4 additions & 2 deletions src/lsst/cmservice/routers/campaigns.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ async def post_campaign(
campaign = db.Campaign(**campaign_create.dict())
session.add(campaign)
await session.refresh(campaign)
return campaign
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return campaign


@router.delete(
Expand Down Expand Up @@ -105,6 +106,7 @@ async def update_production(
for var, value in vars(campaign_update).items():
setattr(campaign, var, value)
await session.refresh(campaign)
return campaign
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return campaign
6 changes: 4 additions & 2 deletions src/lsst/cmservice/routers/groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ async def post_group(
group = db.Group(**group_create.dict())
session.add(group)
await session.refresh(group)
return group
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return group


@router.delete(
Expand Down Expand Up @@ -105,6 +106,7 @@ async def update_production(
for var, value in vars(group_update).items():
setattr(group, var, value)
await session.refresh(group)
return group
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return group
6 changes: 4 additions & 2 deletions src/lsst/cmservice/routers/productions.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@ async def post_production(
production = db.Production(**production_create.dict())
session.add(production)
await session.refresh(production)
return production
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return production


@router.delete(
Expand Down Expand Up @@ -100,6 +101,7 @@ async def update_production(
for var, value in vars(production_update).items():
setattr(production, var, value)
await session.refresh(production)
return production
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return production
6 changes: 4 additions & 2 deletions src/lsst/cmservice/routers/steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ async def post_step(
step = db.Step(**step_create.dict())
session.add(step)
await session.refresh(step)
return step
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return step


@router.delete(
Expand Down Expand Up @@ -105,6 +106,7 @@ async def update_production(
for var, value in vars(step_update).items():
setattr(step, var, value)
await session.refresh(step)
return step
except IntegrityError as e:
raise HTTPException(422, detail=str(e)) from e
else:
return step

0 comments on commit 62dc263

Please sign in to comment.