Skip to content

Commit

Permalink
Merge pull request #8334 from cclauss/ruff-rule-UP007
Browse files Browse the repository at this point in the history
ruff rule UP007: Use X | Y for type annotations
  • Loading branch information
cdrini authored Sep 25, 2023
2 parents 126af2b + acd3116 commit ea3c4ac
Show file tree
Hide file tree
Showing 9 changed files with 24 additions and 24 deletions.
6 changes: 3 additions & 3 deletions openlibrary/solr/data_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ class DataProvider:
"""

def __init__(self) -> None:
self.ia_cache: dict[str, Optional[dict]] = {}
self.ia_cache: dict[str, dict | None] = {}

@staticmethod
async def _get_lite_metadata(ocaids: list[str], _recur_depth=0, _max_recur_depth=3):
Expand Down Expand Up @@ -285,7 +285,7 @@ def get_editions_of_work(self, work):
"""
raise NotImplementedError()

def get_work_ratings(self, work_key: str) -> Optional[WorkRatingsSummary]:
def get_work_ratings(self, work_key: str) -> WorkRatingsSummary | None:
raise NotImplementedError()

def get_work_reading_log(self, work_key: str) -> WorkReadingLogSolrSummary | None:
Expand Down Expand Up @@ -318,7 +318,7 @@ async def get_document(self, key):
logger.info("get_document %s", key)
return self._withKey(key)

def get_work_ratings(self, work_key: str) -> Optional[WorkRatingsSummary]:
def get_work_ratings(self, work_key: str) -> WorkRatingsSummary | None:
work_id = int(work_key[len('/works/OL') : -len('W')])
return Ratings.get_work_ratings_summary(work_id)

Expand Down
2 changes: 1 addition & 1 deletion openlibrary/solr/query_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def luqum_parser(query: str) -> Item:
"""
tree = parser.parse(query)

def find_next_word(item: Item) -> Optional[tuple[Word, Optional[BaseOperation]]]:
def find_next_word(item: Item) -> tuple[Word, BaseOperation | None] | None:
if isinstance(item, Word):
return item, None
elif isinstance(item, BaseOperation) and isinstance(item.children[0], Word):
Expand Down
14 changes: 7 additions & 7 deletions openlibrary/solr/update_edition.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ def key(self):
return self.edition['key']

@property
def title(self) -> Optional[str]:
def title(self) -> str | None:
return self.get('title')

@property
def subtitle(self) -> Optional[str]:
def subtitle(self) -> str | None:
return self.get('subtitle')

@property
Expand All @@ -60,7 +60,7 @@ def alternative_title(self) -> set[str]:
return result

@property
def cover_i(self) -> Optional[int]:
def cover_i(self) -> int | None:
return next(
(cover_id for cover_id in self.get('covers', []) if cover_id != -1), None
)
Expand All @@ -83,7 +83,7 @@ def publisher(self) -> list[str]:
)

@property
def number_of_pages(self) -> Optional[int]:
def number_of_pages(self) -> int | None:
try:
return int(self.get('number_of_pages')) or None
except (TypeError, ValueError): # int(None) -> TypeErr, int("vii") -> ValueErr
Expand All @@ -110,19 +110,19 @@ def lccn(self) -> list[str]:
return uniq(lccn.strip() for lccn in self.get('lccn', []))

@property
def publish_date(self) -> Optional[str]:
def publish_date(self) -> str | None:
return self.get('publish_date')

@property
def publish_year(self) -> Optional[int]:
def publish_year(self) -> int | None:
if self.publish_date:
m = re_year.search(self.publish_date)
return int(m.group(1)) if m else None
else:
return None

@property
def ia(self) -> Optional[str]:
def ia(self) -> str | None:
ocaid = self.get('ocaid')
return ocaid.strip() if ocaid else None

Expand Down
10 changes: 5 additions & 5 deletions openlibrary/solr/update_work.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
data_provider = cast(DataProvider, None)

solr_base_url = None
solr_next: Optional[bool] = None
solr_next: bool | None = None


def get_solr_base_url():
Expand Down Expand Up @@ -187,8 +187,8 @@ def pick_cover_edition(editions, work_cover_id):
)


def pick_number_of_pages_median(editions: list[dict]) -> Optional[int]:
def to_int(x: Any) -> Optional[int]:
def pick_number_of_pages_median(editions: list[dict]) -> int | None:
def to_int(x: Any) -> int | None:
try:
return int(x) or None
except (TypeError, ValueError): # int(None) -> TypeErr, int("vii") -> ValueErr
Expand Down Expand Up @@ -1245,7 +1245,7 @@ async def update_work(work: dict) -> list[SolrUpdateRequest]:

async def update_author(
akey, a=None, handle_redirects=True
) -> Optional[list[SolrUpdateRequest]]:
) -> list[SolrUpdateRequest] | None:
"""
Get the Solr requests necessary to insert/update/delete an Author in Solr.
:param akey: The author key, e.g. /authors/OL23A
Expand Down Expand Up @@ -1553,7 +1553,7 @@ def load_configs(
c_host: str,
c_config: str,
c_data_provider: (
Union[DataProvider, Literal['default', 'legacy', 'external']]
DataProvider | Literal["default", "legacy", "external"]
) = 'default',
) -> DataProvider:
host = web.lstrips(c_host, "http://").strip("/")
Expand Down
2 changes: 1 addition & 1 deletion openlibrary/utils/solr.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get(
key: str,
fields: list[str] | None = None,
doc_wrapper: Callable[[dict], T] = web.storage,
) -> Optional[T]:
) -> T | None:
"""Get a specific item from solr"""
logger.info(f"solr /get: {key}, {fields}")
resp = self.session.get(
Expand Down
4 changes: 1 addition & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,8 @@ max-statements = 70
"openlibrary/plugins/upstream/borrow.py" = ["BLE001", "E722"]
"openlibrary/plugins/upstream/models.py" = ["BLE001"]
"openlibrary/plugins/upstream/utils.py" = ["BLE001"]
"openlibrary/solr/*" = ["UP007"]
"openlibrary/solr/solr_types.py" = ["UP007"]
"openlibrary/solr/update_work.py" = ["C901", "E722", "PLR0912", "PLR0915"]
"openlibrary/utils/solr.py" = ["UP007"]
"scripts/solr_*" = ["UP007"]
"openlibrary/utils/retry.py" = ["BLE001"]
"openlibrary/utils/schema.py" = ["PERF402"]
"openlibrary/utils/tests/test_retry.py" = ["PT012", "PT017"]
Expand Down
2 changes: 1 addition & 1 deletion scripts/solr_builder/solr_builder/fn_to_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def __init__(self, fn: typing.Callable):
description=docs.split(':param', 1)[0],
formatter_class=ArgumentDefaultsHelpFormatter,
)
self.args: typing.Optional[Namespace] = None
self.args: Namespace | None = None
for arg in arg_names:
optional = arg in defaults
cli_name = arg.replace('_', '-')
Expand Down
6 changes: 4 additions & 2 deletions scripts/solr_builder/tests/test_fn_to_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def test_parse_docs(self):

def test_type_to_argparse(self):
assert FnToCLI.type_to_argparse(int) == {'type': int}
assert FnToCLI.type_to_argparse(typing.Optional[int]) == {'type': int}
assert FnToCLI.type_to_argparse(typing.Optional[int]) == { # noqa: UP007
'type': int
}
assert FnToCLI.type_to_argparse(bool) == {
'type': bool,
'action': BooleanOptionalAction,
Expand All @@ -43,5 +45,5 @@ def test_type_to_argparse(self):
}

def test_is_optional(self):
assert FnToCLI.is_optional(typing.Optional[int])
assert FnToCLI.is_optional(typing.Optional[int]) # noqa: UP007
assert not FnToCLI.is_optional(int)
2 changes: 1 addition & 1 deletion scripts/solr_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def read_records(self, max_fetches=10):
self.offset = d['offset']


def find_keys(d: Union[dict, list]) -> Iterator[str]:
def find_keys(d: dict | list) -> Iterator[str]:
"""
Find any keys in the given dict or list.
Expand Down

0 comments on commit ea3c4ac

Please sign in to comment.