PEP8 notes.py

An example of how we can start migrating the codebase to PEP8:

- enable invalid-name at the top
- use bazel run pylib:pylint to identify names that need renaming
- use PyCharm or similar to rename the functions/variables
- in the cases where the conversion is not just snake_case, use
.register_deprecated_aliases()

+ removed the __repr__() definition, it dumps all the note content
and obscures the error message
This commit is contained in:
Damien Elmes 2021-06-26 11:38:59 +10:00
parent 0ddd316388
commit fee486aaa1
3 changed files with 32 additions and 36 deletions

View File

@ -1,15 +1,17 @@
# Copyright: Ankitects Pty Ltd and contributors # Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# pylint: enable=invalid-name
from __future__ import annotations from __future__ import annotations
import copy import copy
import pprint
from typing import Any, List, NewType, Optional, Sequence, Tuple, Union from typing import Any, List, NewType, Optional, Sequence, Tuple, Union
import anki # pylint: disable=unused-import import anki # pylint: disable=unused-import
import anki._backend.backend_pb2 as _pb import anki._backend.backend_pb2 as _pb
from anki import hooks from anki import hooks
from anki._legacy import DeprecatedNamesMixin
from anki.consts import MODEL_STD from anki.consts import MODEL_STD
from anki.models import NotetypeDict, NotetypeId, TemplateDict from anki.models import NotetypeDict, NotetypeId, TemplateDict
from anki.utils import joinFields from anki.utils import joinFields
@ -21,7 +23,7 @@ NoteFieldsCheckResult = _pb.NoteFieldsCheckResponse.State
NoteId = NewType("NoteId", int) NoteId = NewType("NoteId", int)
class Note: class Note(DeprecatedNamesMixin):
# not currently exposed # not currently exposed
flags = 0 flags = 0
data = "" data = ""
@ -47,18 +49,18 @@ class Note:
self._load_from_backend_note(self.col._backend.new_note(notetype_id)) self._load_from_backend_note(self.col._backend.new_note(notetype_id))
def load(self) -> None: def load(self) -> None:
n = self.col._backend.get_note(self.id) note = self.col._backend.get_note(self.id)
assert n assert note
self._load_from_backend_note(n) self._load_from_backend_note(note)
def _load_from_backend_note(self, n: _pb.Note) -> None: def _load_from_backend_note(self, note: _pb.Note) -> None:
self.id = NoteId(n.id) self.id = NoteId(note.id)
self.guid = n.guid self.guid = note.guid
self.mid = NotetypeId(n.notetype_id) self.mid = NotetypeId(note.notetype_id)
self.mod = n.mtime_secs self.mod = note.mtime_secs
self.usn = n.usn self.usn = note.usn
self.tags = list(n.tags) self.tags = list(note.tags)
self.fields = list(n.fields) self.fields = list(note.fields)
self._fmap = self.col.models.fieldMap(self.model()) self._fmap = self.col.models.fieldMap(self.model())
def _to_backend_note(self) -> _pb.Note: def _to_backend_note(self) -> _pb.Note:
@ -81,12 +83,7 @@ class Note:
note=self._to_backend_note(), skip_undo_entry=True note=self._to_backend_note(), skip_undo_entry=True
) )
def __repr__(self) -> str: def joined_fields(self) -> str:
d = dict(self.__dict__)
del d["col"]
return f"{super().__repr__()} {pprint.pformat(d, width=300)}"
def joinedFields(self) -> str:
return joinFields(self.fields) return joinFields(self.fields)
def ephemeral_card( def ephemeral_card(
@ -145,20 +142,20 @@ class Note:
def values(self) -> List[str]: def values(self) -> List[str]:
return self.fields return self.fields
def items(self) -> List[Tuple[Any, Any]]: def items(self) -> List[Tuple[str, str]]:
return [(f["name"], self.fields[ord]) for ord, f in sorted(self._fmap.values())] return [(f["name"], self.fields[ord]) for ord, f in sorted(self._fmap.values())]
def _fieldOrd(self, key: str) -> Any: def _field_index(self, key: str) -> int:
try: try:
return self._fmap[key][0] return self._fmap[key][0]
except Exception as exc: except Exception as exc:
raise KeyError(key) from exc raise KeyError(key) from exc
def __getitem__(self, key: str) -> str: def __getitem__(self, key: str) -> str:
return self.fields[self._fieldOrd(key)] return self.fields[self._field_index(key)]
def __setitem__(self, key: str, value: str) -> None: def __setitem__(self, key: str, value: str) -> None:
self.fields[self._fieldOrd(key)] = value self.fields[self._field_index(key)] = value
def __contains__(self, key: str) -> bool: def __contains__(self, key: str) -> bool:
return key in self._fmap return key in self._fmap
@ -171,26 +168,22 @@ class Note:
def remove_tag(self, tag: str) -> None: def remove_tag(self, tag: str) -> None:
rem = [] rem = []
for t in self.tags: for tag_ in self.tags:
if t.lower() == tag.lower(): if tag_.lower() == tag.lower():
rem.append(t) rem.append(tag_)
for r in rem: for tag_ in rem:
self.tags.remove(r) self.tags.remove(tag_)
def add_tag(self, tag: str) -> None: def add_tag(self, tag: str) -> None:
"Add tag. Duplicates will be stripped on save." "Add tag. Duplicates will be stripped on save."
self.tags.append(tag) self.tags.append(tag)
def stringTags(self) -> Any: def string_tags(self) -> Any:
return self.col.tags.join(self.col.tags.canonify(self.tags)) return self.col.tags.join(self.col.tags.canonify(self.tags))
def setTagsFromStr(self, tags: str) -> None: def set_tags_from_str(self, tags: str) -> None:
self.tags = self.col.tags.split(tags) self.tags = self.col.tags.split(tags)
hasTag = has_tag
addTag = add_tag
delTag = remove_tag
# Unique/duplicate/cloze check # Unique/duplicate/cloze check
################################################## ##################################################
@ -198,3 +191,6 @@ class Note:
return self.col._backend.note_fields_check(self._to_backend_note()).state return self.col._backend.note_fields_check(self._to_backend_note()).state
dupeOrEmpty = duplicate_or_empty = fields_check dupeOrEmpty = duplicate_or_empty = fields_check
Note.register_deprecated_aliases(delTag=Note.remove_tag, _fieldOrd=Note._field_index)

View File

@ -173,7 +173,7 @@ class TemplateRenderContext:
fields = dict(self._note.items()) fields = dict(self._note.items())
# add (most) special fields # add (most) special fields
fields["Tags"] = self._note.stringTags().strip() fields["Tags"] = self._note.string_tags().strip()
fields["Type"] = self._note_type["name"] fields["Type"] = self._note_type["name"]
fields["Deck"] = self._col.decks.name(self._card.current_deck_id()) fields["Deck"] = self._col.decks.name(self._card.current_deck_id())
fields["Subdeck"] = DeckManager.basename(fields["Deck"]) fields["Subdeck"] = DeckManager.basename(fields["Deck"])

View File

@ -628,7 +628,7 @@ $editorToolbar.then(({{ toolbar }}) => toolbar.appendGroup({{
if self.tags.col != self.mw.col: if self.tags.col != self.mw.col:
self.tags.setCol(self.mw.col) self.tags.setCol(self.mw.col)
if not self.tags.text() or not self.addMode: if not self.tags.text() or not self.addMode:
self.tags.setText(self.note.stringTags().strip()) self.tags.setText(self.note.string_tags().strip())
def on_tag_focus_lost(self) -> None: def on_tag_focus_lost(self) -> None:
self.note.tags = self.mw.col.tags.split(self.tags.text()) self.note.tags = self.mw.col.tags.split(self.tags.text())