Skip to content

Commit 31c1ce3

Browse files
authored
Merge pull request internetarchive#10994 from internetarchive/misc-typehints
add typehints to misc files
2 parents 19045c1 + 5296839 commit 31c1ce3

File tree

3 files changed

+40
-45
lines changed

3 files changed

+40
-45
lines changed

openlibrary/core/models.py

Lines changed: 35 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def process(v):
122122
return history
123123

124124
@cache.memoize(engine="memcache", key=lambda self: ("d" + self.key, "h"))
125-
def _get_history_preview(self):
125+
def _get_history_preview(self) -> dict[str, list[dict]]:
126126
h = {}
127127
if self.revision < 5:
128128
h['recent'] = self._get_versions(limit=5)
@@ -133,7 +133,7 @@ def _get_history_preview(self):
133133
h['recent'] = self._get_versions(limit=4)
134134
return h
135135

136-
def _get_versions(self, limit, offset=0):
136+
def _get_versions(self, limit: int, offset: int = 0) -> list[dict]:
137137
q = {"key": self.key, "limit": limit, "offset": offset}
138138
versions = self._site.versions(q)
139139
for v in versions:
@@ -153,14 +153,16 @@ def get_most_recent_change(self):
153153
else:
154154
return preview.initial[0]
155155

156-
def prefetch(self):
156+
def prefetch(self) -> None:
157157
"""Prefetch all the anticipated data."""
158158
preview = self.get_history_preview()
159159
authors = {v.author.key for v in preview.initial + preview.recent if v.author}
160160
# preload them
161161
self._site.get_many(list(authors))
162162

163-
def _make_url(self, label: str | None, suffix: str, relative=True, **params):
163+
def _make_url(
164+
self, label: str | None, suffix: str, relative: bool = True, **params
165+
) -> str:
164166
"""Make url of the form $key/$label$suffix?$params."""
165167
if label is not None:
166168
u = self.key + "/" + urlsafe(label) + suffix
@@ -172,7 +174,7 @@ def _make_url(self, label: str | None, suffix: str, relative=True, **params):
172174
u = _get_ol_base_url() + u
173175
return u
174176

175-
def get_url(self, suffix="", **params) -> str:
177+
def get_url(self, suffix: str = "", **params) -> str:
176178
"""Constructs a URL for this page with given suffix and query params.
177179
178180
The suffix is added to the URL of the page and query params are appended after adding "?".
@@ -191,7 +193,7 @@ def get_url_suffix(self) -> str | None:
191193
"""
192194
return None
193195

194-
def _get_lists(self, limit=50, offset=0, sort=True):
196+
def _get_lists(self, limit: int = 50, offset: int = 0, sort: bool = True):
195197
# cache the default case
196198
if limit == 50 and offset == 0:
197199
keys = self._get_lists_cached()
@@ -207,7 +209,7 @@ def _get_lists(self, limit=50, offset=0, sort=True):
207209
def _get_lists_cached(self):
208210
return self._get_lists_uncached(limit=50, offset=0)
209211

210-
def _get_lists_uncached(self, limit, offset):
212+
def _get_lists_uncached(self, limit: int, offset: int) -> list[str]:
211213
q = {
212214
"type": "/type/list",
213215
"seeds": {"key": self.key},
@@ -216,7 +218,7 @@ def _get_lists_uncached(self, limit, offset):
216218
}
217219
return self._site.things(q)
218220

219-
def _get_d(self):
221+
def _get_d(self) -> dict:
220222
"""Returns the data that goes into memcache as d/$self.key.
221223
Used to measure the memcache usage.
222224
"""
@@ -241,7 +243,7 @@ class Edition(Thing):
241243
def url(self, suffix="", **params):
242244
return self.get_url(suffix, **params)
243245

244-
def get_url_suffix(self):
246+
def get_url_suffix(self) -> str:
245247
return self.title or "untitled"
246248

247249
def __repr__(self):
@@ -253,12 +255,13 @@ def full_title(self):
253255
# retained for backward-compatibility. Is anybody using this really?
254256
return self.title
255257

256-
def get_publish_year(self):
258+
def get_publish_year(self) -> int | None:
257259
if self.publish_date:
258260
m = web.re_compile(r"(\d\d\d\d)").search(self.publish_date)
259261
return m and int(m.group(1))
262+
return None
260263

261-
def get_lists(self, limit=50, offset=0, sort=True):
264+
def get_lists(self, limit: int = 50, offset: int = 0, sort: bool = True):
262265
return self._get_lists(limit=limit, offset=offset, sort=sort)
263266

264267
def get_ebook_info(self):
@@ -309,33 +312,33 @@ def get_ebook_info(self):
309312
def get_ia_collections(self):
310313
return self.get_ia_meta_fields().get("collection", [])
311314

312-
def is_access_restricted(self):
315+
def is_access_restricted(self) -> bool:
313316
collections = self.get_ia_collections()
314317
return bool(collections) and (
315318
'printdisabled' in collections
316319
or self.get_ia_meta_fields().get("access-restricted") is True
317320
)
318321

319-
def is_in_private_collection(self):
322+
def is_in_private_collection(self) -> bool:
320323
"""Private collections are lendable books that should not be
321324
linked/revealed from OL
322325
"""
323326
return private_collection_in(self.get_ia_collections())
324327

325-
def in_borrowable_collection(self):
328+
def in_borrowable_collection(self) -> bool:
326329
collections = self.get_ia_collections()
327330
return ('inlibrary' in collections) and not self.is_in_private_collection()
328331

329-
def get_waitinglist(self):
332+
def get_waitinglist(self) -> list[WaitingLoan]:
330333
"""Returns list of records for all users currently waiting for this book."""
331334
return waitinglist.get_waitinglist_for_book(self.key)
332335

333336
@property # type: ignore[misc]
334-
def ia_metadata(self):
337+
def ia_metadata(self) -> dict:
335338
ocaid = self.get('ocaid')
336339
return get_metadata(ocaid) if ocaid else {}
337340

338-
def get_waitinglist_size(self, ia=False):
341+
def get_waitinglist_size(self) -> int:
339342
"""Returns the number of people on waiting list to borrow this book."""
340343
return waitinglist.get_waitinglist_size(self.key)
341344

@@ -871,18 +874,14 @@ def merge_remote_ids(
871874

872875

873876
class User(Thing):
874-
def get_default_preferences(self):
877+
def get_default_preferences(self) -> dict[str, str]:
875878
return {'update': 'no', 'public_readlog': 'no', 'type': 'preferences'}
876879
# New users are now public by default for new patrons
877880
# As of 2020-05, OpenLibraryAccount.create will
878881
# explicitly set public_readlog: 'yes'.
879882
# Legacy accounts w/ no public_readlog key
880883
# will continue to default to 'no'
881884

882-
def get_status(self):
883-
account = self.get_account() or {}
884-
return account.get("status")
885-
886885
def get_usergroups(self):
887886
keys = self._site.things({'type': '/type/usergroup', 'members': self.key})
888887
return self._site.get_many(keys)
@@ -893,14 +892,14 @@ def get_account(self):
893892
username = self.get_username()
894893
return accounts.find(username=username)
895894

896-
def get_email(self):
895+
def get_email(self) -> str | None:
897896
account = self.get_account() or {}
898897
return account.get("email")
899898

900-
def get_username(self):
899+
def get_username(self) -> str:
901900
return self.key.split("/")[-1]
902901

903-
def preferences(self, use_store=False):
902+
def preferences(self, use_store: bool = False):
904903
key = f"{self.key}/preferences"
905904
if use_store:
906905
prefs = web.ctx.site.store.get(key)
@@ -912,8 +911,8 @@ def preferences(self, use_store=False):
912911
) or self.get_default_preferences()
913912

914913
def save_preferences(
915-
self, new_prefs, msg='updating user preferences', use_store=False
916-
):
914+
self, new_prefs, msg='updating user preferences', use_store: bool = False
915+
) -> None:
917916
key = f'{self.key}/preferences'
918917
if use_store:
919918
old_prefs = self.preferences(use_store=use_store)
@@ -934,12 +933,12 @@ def save_preferences(
934933
# Save a copy of the patron's preferences to the store
935934
self.save_preferences(new_prefs, msg=msg, use_store=True)
936935

937-
def is_usergroup_member(self, usergroup):
936+
def is_usergroup_member(self, usergroup: str) -> bool:
938937
if not usergroup.startswith('/usergroup/'):
939938
usergroup = f'/usergroup/{usergroup}'
940939
return usergroup in [g.key for g in self.usergroups]
941940

942-
def is_subscribed_user(self, username):
941+
def is_subscribed_user(self, username: str) -> int:
943942
my_username = self.get_username()
944943
return (
945944
PubSub.is_subscribed(my_username, username)
@@ -953,19 +952,19 @@ def has_cookie(self, name):
953952
def is_printdisabled(self):
954953
return web.cookies().get('pd')
955954

956-
def is_admin(self):
955+
def is_admin(self) -> bool:
957956
return self.is_usergroup_member('/usergroup/admin')
958957

959-
def is_librarian(self):
958+
def is_librarian(self) -> bool:
960959
return self.is_usergroup_member('/usergroup/librarians')
961960

962-
def is_super_librarian(self):
961+
def is_super_librarian(self) -> bool:
963962
return self.is_usergroup_member('/usergroup/super-librarians')
964963

965-
def is_beta_tester(self):
964+
def is_beta_tester(self) -> bool:
966965
return self.is_usergroup_member('/usergroup/beta-testers')
967966

968-
def is_read_only(self):
967+
def is_read_only(self) -> bool:
969968
return self.is_usergroup_member('/usergroup/read-only')
970969

971970
def get_lists(self, seed=None, limit=100, offset=0, sort=True):
@@ -989,7 +988,7 @@ def get_lists(self, seed=None, limit=100, offset=0, sort=True):
989988

990989
@classmethod
991990
# @cache.memoize(engine="memcache", key="user-avatar")
992-
def get_avatar_url(cls, username):
991+
def get_avatar_url(cls, username: str) -> str:
993992
username = username.split('/people/')[-1]
994993
user = web.ctx.site.get(f'/people/{username}')
995994
itemname = user.get_account().get('internetarchive_itemname')
@@ -1014,7 +1013,7 @@ def _get_lists_uncached(self, seed=None, limit=100, offset=0):
10141013

10151014
return self._site.things(q)
10161015

1017-
def new_list(self, name, description, seeds, tags=None):
1016+
def new_list(self, name: str, description: str, seeds, tags=None):
10181017
tags = tags or []
10191018
"""Creates a new list object with given name, description, and seeds.
10201019
@@ -1047,10 +1046,6 @@ def new_list(self, name, description, seeds, tags=None):
10471046
}
10481047
return self._site.new(key, doc)
10491048

1050-
def is_waiting_for(self, book):
1051-
"""Returns True if this user is waiting to loan given book."""
1052-
return waitinglist.is_user_waiting_for(self.key, book.key)
1053-
10541049
def get_waitinglist(self):
10551050
"""Returns list of records for all the books the user is currently waiting for."""
10561051
return waitinglist.get_waitinglist_for_user(self.key)

openlibrary/core/waitinglist.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def update(self, **kw):
156156
dict.update(self, kw)
157157

158158

159-
def get_waitinglist_for_book(book_key):
159+
def get_waitinglist_for_book(book_key) -> list[WaitingLoan]:
160160
"""Returns the list of records for the users waiting for the given book.
161161
162162
This is an admin-only feature. It works only if the current user is an admin.

openlibrary/plugins/upstream/models.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -854,12 +854,12 @@ class SubjectPerson(Subject):
854854
class User(models.User):
855855
displayname: str | None
856856

857-
def get_name(self):
857+
def get_name(self) -> str:
858858
return self.displayname or self.key.split('/')[-1]
859859

860860
name = property(get_name)
861861

862-
def get_edit_history(self, limit=10, offset=0):
862+
def get_edit_history(self, limit: int = 10, offset: int = 0):
863863
return web.ctx.site.versions(
864864
{"author": self.key, "limit": limit, "offset": offset}
865865
)
@@ -875,13 +875,13 @@ def get_creation_info(self):
875875
)[0]
876876
return web.storage({"ip": d.ip, "member_since": d.created})
877877

878-
def get_edit_count(self):
878+
def get_edit_count(self) -> int:
879879
if web.ctx.path.startswith("/admin"):
880880
return web.ctx.site._request('/count_edits_by_user', data={"key": self.key})
881881
else:
882882
return 0
883883

884-
def get_loan_count(self):
884+
def get_loan_count(self) -> int:
885885
return len(borrow.get_loans(self))
886886

887887
def get_loans(self):

0 commit comments

Comments
 (0)