From 6cda6a2e5d8315ff6bf1795987436a91bcabd9d1 Mon Sep 17 00:00:00 2001 From: un-pogaz <46523284+un-pogaz@users.noreply.github.com> Date: Fri, 24 Jan 2025 11:14:17 +0100 Subject: [PATCH] write better list/set/dict comprehensions (extra-edit) --- manual/custom.py | 2 +- recipes/1843.recipe | 2 +- recipes/andhrajyothy_ap.recipe | 2 +- recipes/andhrajyothy_tel.recipe | 2 +- recipes/barrons.recipe | 2 +- recipes/boston_globe_print_edition.recipe | 2 +- recipes/chronicle_higher_ed.recipe | 2 +- recipes/economist.recipe | 2 +- recipes/economist_free.recipe | 2 +- recipes/epw_magazine.recipe | 2 +- recipes/fokus.recipe | 2 +- recipes/foreign_policy.recipe | 2 +- recipes/frontline.recipe | 2 +- recipes/hindu.recipe | 2 +- recipes/hindustan_times_print.recipe | 2 +- recipes/history_today.recipe | 2 +- recipes/mit_technology_review.recipe | 2 +- recipes/phillosophy_now.recipe | 2 +- recipes/sportstar.recipe | 2 +- recipes/strange_horizons.recipe | 2 +- src/calibre/db/legacy.py | 2 +- src/calibre/ebooks/metadata/sources/amazon.py | 3 +-- src/calibre/ebooks/oeb/iterator/book.py | 2 +- src/calibre/ebooks/pdf/reflow.py | 6 ++---- src/calibre/gui2/custom_column_widgets.py | 2 +- src/calibre/gui2/tag_browser/model.py | 2 +- src/calibre/gui2/tag_browser/ui.py | 2 +- src/calibre/library/catalogs/epub_mobi.py | 2 +- src/calibre/spell/dictionary.py | 5 ++--- src/calibre/utils/bibtex.py | 2 +- src/calibre/utils/fonts/sfnt/subset.py | 2 +- 31 files changed, 33 insertions(+), 37 deletions(-) diff --git a/manual/custom.py b/manual/custom.py index 6d7599d688..b385d92074 100644 --- a/manual/custom.py +++ b/manual/custom.py @@ -198,7 +198,7 @@ details and examples. lines += [f'.. _calibredb-{language}-{cmd}:', ''] lines += [cmd, '~'*20, ''] usage = parser.usage.strip() - usage = list(usage.replace('%prog', 'calibredb').splitlines()) + usage = usage.replace('%prog', 'calibredb').splitlines() cmdline = ' '+usage[0] usage = usage[1:] usage = [re.sub(rf'({cmd})([^a-zA-Z0-9])', r':command:`\1`\2', i) for i in usage] diff --git a/recipes/1843.recipe b/recipes/1843.recipe index 81c1437ee4..5755461574 100644 --- a/recipes/1843.recipe +++ b/recipes/1843.recipe @@ -262,7 +262,7 @@ class Economist(BasicNewsRecipe): url = 'file:///' + pt.name feeds_dict[section].append({'title': title, 'url': url, 'description': desc}) self.log('\t', title, '\n\t\t', desc) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def populate_article_metadata(self, article, soup, first): article.url = soup.find('h1')['title'] diff --git a/recipes/andhrajyothy_ap.recipe b/recipes/andhrajyothy_ap.recipe index f2833ddb18..0afb08b1ae 100644 --- a/recipes/andhrajyothy_ap.recipe +++ b/recipes/andhrajyothy_ap.recipe @@ -76,7 +76,7 @@ class andhra(BasicNewsRecipe): if snaps['ObjectType'] == 4: continue feeds_dict[section].append({'title': '', 'url': url}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def preprocess_raw_html(self, raw, *a): data = json.loads(raw) diff --git a/recipes/andhrajyothy_tel.recipe b/recipes/andhrajyothy_tel.recipe index ff7195112b..d10c1bd87e 100644 --- a/recipes/andhrajyothy_tel.recipe +++ b/recipes/andhrajyothy_tel.recipe @@ -76,7 +76,7 @@ class andhra(BasicNewsRecipe): if snaps['ObjectType'] == 4: continue feeds_dict[section].append({'title': '', 'url': url}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def preprocess_raw_html(self, raw, *a): data = json.loads(raw) diff --git a/recipes/barrons.recipe b/recipes/barrons.recipe index a80ffbcf46..898abe230b 100644 --- a/recipes/barrons.recipe +++ b/recipes/barrons.recipe @@ -127,7 +127,7 @@ class barrons(BasicNewsRecipe): desc += ' | ' + self.tag_to_string(summ) self.log('\t', title, ' ', url, '\n\t', desc) ans[section].append({'title': title, 'url': url, 'description': desc}) - return [(section, articles) for section, articles in ans.items()] + return list(ans.items()) def print_version(self, url): return url.split('?')[0].replace('/articles/', '/amp/articles/') diff --git a/recipes/boston_globe_print_edition.recipe b/recipes/boston_globe_print_edition.recipe index 2a596c4126..515bb42270 100644 --- a/recipes/boston_globe_print_edition.recipe +++ b/recipes/boston_globe_print_edition.recipe @@ -95,7 +95,7 @@ class BostonGlobePrint(BasicNewsRecipe): self.log(section, '\n\t', title, '\n\t', desc, '\n\t\t', url) feeds_dict[section].append({'title': title, 'url': url, 'description': desc}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def preprocess_raw_html(self, raw_html, url): soup = self.index_to_soup(raw_html) diff --git a/recipes/chronicle_higher_ed.recipe b/recipes/chronicle_higher_ed.recipe index 84087d3e44..795aac4276 100644 --- a/recipes/chronicle_higher_ed.recipe +++ b/recipes/chronicle_higher_ed.recipe @@ -77,7 +77,7 @@ class Chronicle(BasicNewsRecipe): if section_title not in feeds: feeds[section_title] = [] feeds[section_title] += articles - ans = [(key, val) for key, val in feeds.items()] + ans = list(feeds.items()) return ans def preprocess_html(self, soup): diff --git a/recipes/economist.recipe b/recipes/economist.recipe index cb6aa782f4..ddb96b6219 100644 --- a/recipes/economist.recipe +++ b/recipes/economist.recipe @@ -382,7 +382,7 @@ class Economist(BasicNewsRecipe): url = 'file:///' + pt.name feeds_dict[section].append({'title': title, 'url': url, 'description': desc}) self.log('\t', title, '\n\t\t', desc) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def populate_article_metadata(self, article, soup, first): if not self.from_archive: diff --git a/recipes/economist_free.recipe b/recipes/economist_free.recipe index cb6aa782f4..ddb96b6219 100644 --- a/recipes/economist_free.recipe +++ b/recipes/economist_free.recipe @@ -382,7 +382,7 @@ class Economist(BasicNewsRecipe): url = 'file:///' + pt.name feeds_dict[section].append({'title': title, 'url': url, 'description': desc}) self.log('\t', title, '\n\t\t', desc) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def populate_article_metadata(self, article, soup, first): if not self.from_archive: diff --git a/recipes/epw_magazine.recipe b/recipes/epw_magazine.recipe index 105ee34f7c..ff258fbc16 100644 --- a/recipes/epw_magazine.recipe +++ b/recipes/epw_magazine.recipe @@ -72,5 +72,5 @@ class epw(BasicNewsRecipe): if section_title not in feeds: feeds[section_title] = [] feeds[section_title] += articles - ans = [(key, val) for key, val in feeds.items()] + ans = list(feeds.items()) return ans diff --git a/recipes/fokus.recipe b/recipes/fokus.recipe index 206e9750dc..9559086188 100644 --- a/recipes/fokus.recipe +++ b/recipes/fokus.recipe @@ -276,7 +276,7 @@ class Fokus(BasicNewsRecipe): section_to_articles = self.assign_articles_to_sections(sections, articles) # Convert to the expected `list[tuple[str, dict[str, str, str, str]]]` format. - feeds = [(section_url, article_dicts) for section_url, article_dicts in section_to_articles.items()] + feeds = list(section_to_articles.items()) num_articles = sum(len(article_dicts) for article_dicts in section_to_articles.values()) self.log(f'A total of {num_articles} articles belonging to {len(section_to_articles)} sections were kept.') diff --git a/recipes/foreign_policy.recipe b/recipes/foreign_policy.recipe index 10b969c756..2caea2e354 100644 --- a/recipes/foreign_policy.recipe +++ b/recipes/foreign_policy.recipe @@ -86,7 +86,7 @@ class ForeignPolicy(BasicNewsRecipe): desc += ' | ' + self.tag_to_string(dek) self.log('\t', title, url, '\n\t', desc) feeds_dict[current_section].append({'title': title, 'url': url, 'description': desc}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def preprocess_html(self, soup): for img in soup.findAll('img', attrs={'src':True}): diff --git a/recipes/frontline.recipe b/recipes/frontline.recipe index 7a435ac732..b03d8b1470 100644 --- a/recipes/frontline.recipe +++ b/recipes/frontline.recipe @@ -96,4 +96,4 @@ class Frontline(BasicNewsRecipe): continue self.log(section, '\n\t', title, '\n\t', desc, '\n\t\t', url) feeds_dict[section].append({'title': title, 'url': url, 'description': desc}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) diff --git a/recipes/hindu.recipe b/recipes/hindu.recipe index b49539803a..8027919a81 100644 --- a/recipes/hindu.recipe +++ b/recipes/hindu.recipe @@ -134,6 +134,6 @@ class TheHindu(BasicNewsRecipe): desc = 'Page no.' + item['pageno'] + ' | ' + item['teaser_text'] or '' self.log(' ', title, '\n\t', url) feeds_dict[section].append({'title': title, 'url': url, 'description': desc}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) else: return [] diff --git a/recipes/hindustan_times_print.recipe b/recipes/hindustan_times_print.recipe index 9bf5d34f39..dae7044289 100644 --- a/recipes/hindustan_times_print.recipe +++ b/recipes/hindustan_times_print.recipe @@ -98,7 +98,7 @@ class ht(BasicNewsRecipe): desc = page_no self.log('\t', title, ' ', desc) feeds_dict[section].append({'title': title, 'description': desc, 'url': url}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) def preprocess_raw_html(self, raw, *a): diff --git a/recipes/history_today.recipe b/recipes/history_today.recipe index b7f1462567..8be0a0070f 100644 --- a/recipes/history_today.recipe +++ b/recipes/history_today.recipe @@ -85,7 +85,7 @@ class HistoryToday(BasicNewsRecipe): feeds[section_title] = [] feeds[section_title] += articles - ans = [(key, val) for key, val in feeds.items()] + ans = list(feeds.items()) return ans def cleanup(self): diff --git a/recipes/mit_technology_review.recipe b/recipes/mit_technology_review.recipe index 1bc7b4d58c..225ed5c498 100644 --- a/recipes/mit_technology_review.recipe +++ b/recipes/mit_technology_review.recipe @@ -151,7 +151,7 @@ class MitTechnologyReview(BasicNewsRecipe): if section_title not in feeds: feeds[section_title] = [] feeds[section_title] += articles - ans = [(key, val) for key, val in feeds.items()] + ans = list(feeds.items()) return ans def preprocess_html(self, soup): diff --git a/recipes/phillosophy_now.recipe b/recipes/phillosophy_now.recipe index 21fa9ef565..0ed4f64db7 100644 --- a/recipes/phillosophy_now.recipe +++ b/recipes/phillosophy_now.recipe @@ -82,7 +82,7 @@ class PhilosophyNow(BasicNewsRecipe): if section_title not in feeds: feeds[section_title] = [] feeds[section_title] += articles - ans = [(key, val) for key, val in feeds.items()] + ans = list(feeds.items()) return ans # PN changes the content it delivers based on cookies, so the diff --git a/recipes/sportstar.recipe b/recipes/sportstar.recipe index 90ae0cd0ed..cd4781b8d8 100644 --- a/recipes/sportstar.recipe +++ b/recipes/sportstar.recipe @@ -85,7 +85,7 @@ class Sportstar(BasicNewsRecipe): if section_title not in feeds: feeds[section_title] = [] feeds[section_title] += articles - ans = [(key, val) for key, val in feeds.items()] + ans = list(feeds.items()) return ans def preprocess_html(self, soup): diff --git a/recipes/strange_horizons.recipe b/recipes/strange_horizons.recipe index 1fd922b2c1..44b5c847f8 100644 --- a/recipes/strange_horizons.recipe +++ b/recipes/strange_horizons.recipe @@ -65,4 +65,4 @@ class StrangeHorizons(BasicNewsRecipe): self.log(sec, '\n\t', title, '\n\t', desc, '\n\t\t', url) feeds_dict[sec].append({'title': title, 'url': url, 'description': desc}) - return [(section, articles) for section, articles in feeds_dict.items()] + return list(feeds_dict.items()) diff --git a/src/calibre/db/legacy.py b/src/calibre/db/legacy.py index 3532032ef6..5bf057b372 100644 --- a/src/calibre/db/legacy.py +++ b/src/calibre/db/legacy.py @@ -287,7 +287,7 @@ class LibraryDatabase: return [[k, v] for k, v in iteritems(self.new_api.get_usage_count_by_id(field))] def field_id_map(self, field): - return [(k, v) for k, v in iteritems(self.new_api.get_id_map(field))] + return list(iteritems(self.new_api.get_id_map(field))) def get_custom_items_with_ids(self, label=None, num=None): try: diff --git a/src/calibre/ebooks/metadata/sources/amazon.py b/src/calibre/ebooks/metadata/sources/amazon.py index 33fab58364..1bec72010d 100644 --- a/src/calibre/ebooks/metadata/sources/amazon.py +++ b/src/calibre/ebooks/metadata/sources/amazon.py @@ -1395,8 +1395,7 @@ class Amazon(Source): q['field-keywords'] += ' ' + q.pop(f, '') q['field-keywords'] = q['field-keywords'].strip() - encoded_q = {x.encode('utf-8', 'ignore'): y.encode( - 'utf-8', 'ignore') for x, y in q.items()} + encoded_q = {x.encode('utf-8', 'ignore'): y.encode('utf-8', 'ignore') for x, y in q.items()} url_query = urlencode(encoded_q) # amazon's servers want IRIs with unicode characters not percent esaped parts = [] diff --git a/src/calibre/ebooks/oeb/iterator/book.py b/src/calibre/ebooks/oeb/iterator/book.py index f58a870542..efb594f43d 100644 --- a/src/calibre/ebooks/oeb/iterator/book.py +++ b/src/calibre/ebooks/oeb/iterator/book.py @@ -106,7 +106,7 @@ class EbookIterator(BookmarksMixin): def search(self, text, index, backwards=False): from calibre.ebooks.oeb.polish.parsing import parse - pmap = [(i, path) for i, path in enumerate(self.spine)] + pmap = list(enumerate(self.spine)) if backwards: pmap.reverse() q = text.lower() diff --git a/src/calibre/ebooks/pdf/reflow.py b/src/calibre/ebooks/pdf/reflow.py index 64fa4087f7..17e75f3a0d 100644 --- a/src/calibre/ebooks/pdf/reflow.py +++ b/src/calibre/ebooks/pdf/reflow.py @@ -644,8 +644,7 @@ class Region: def collect_stats(self): for column in self.columns: column.collect_stats() - self.average_line_separation = sum([x.average_line_separation for x in - self.columns])/float(len(self.columns)) + self.average_line_separation = sum(x.average_line_separation for x in self.columns)/float(len(self.columns)) def __iter__(self): yield from self.columns @@ -1263,8 +1262,7 @@ class Page: absorb_into = prev_region if self.regions[next_region].line_count >= \ self.regions[prev_region].line_count: - avg_column_count = sum([len(r.columns) for r in - regions])/float(len(regions)) + avg_column_count = sum(len(r.columns) for r in regions)/float(len(regions)) if self.regions[next_region].line_count > \ self.regions[prev_region].line_count \ or abs(avg_column_count - diff --git a/src/calibre/gui2/custom_column_widgets.py b/src/calibre/gui2/custom_column_widgets.py index 8155e5040a..a90ca2f4a3 100644 --- a/src/calibre/gui2/custom_column_widgets.py +++ b/src/calibre/gui2/custom_column_widgets.py @@ -887,7 +887,7 @@ def get_field_list(db, use_defaults=False, pref_data_override=None): for k in fields: if k not in result: result[k] = True - return [(k,v) for k,v in result.items()] + return list(result.items()) def get_custom_columns_to_display_in_editor(db): diff --git a/src/calibre/gui2/tag_browser/model.py b/src/calibre/gui2/tag_browser/model.py index 8af5c2942b..acd478a029 100644 --- a/src/calibre/gui2/tag_browser/model.py +++ b/src/calibre/gui2/tag_browser/model.py @@ -636,7 +636,7 @@ class TagsModel(QAbstractItemModel): # {{{ key, (category_icon_map['user:'] if key.startswith('@') else category_icon_map['custom:']))) if key.startswith('@'): - path_parts = list(key.split('.')) + path_parts = key.split('.') path = '' last_category_node = self.root_item tree_root = self.user_category_node_tree diff --git a/src/calibre/gui2/tag_browser/ui.py b/src/calibre/gui2/tag_browser/ui.py index e386e08807..cf947fc13f 100644 --- a/src/calibre/gui2/tag_browser/ui.py +++ b/src/calibre/gui2/tag_browser/ui.py @@ -105,7 +105,7 @@ class TagBrowserMixin: # {{{ proxy_md = db.new_api.get_proxy_metadata(db.id(idx.row())) items = proxy_md.get(current_cat) if isinstance(items, str): - items = [items,] + items = [items] if items: items_title = _('{category} for current book').format(category=cdn) if len(items) > 4: diff --git a/src/calibre/library/catalogs/epub_mobi.py b/src/calibre/library/catalogs/epub_mobi.py index 75b9140059..ad2dc21491 100644 --- a/src/calibre/library/catalogs/epub_mobi.py +++ b/src/calibre/library/catalogs/epub_mobi.py @@ -201,7 +201,7 @@ class EPUB_MOBI(CatalogPlugin): if opts.preset not in available_presets: if available_presets: print(_('Error: Preset "{}" not found.').format(opts.preset)) - print(_('Stored presets: {}').format(', '.join(list(sorted(available_presets.keys()))))) + print(_('Stored presets: {}').format(', '.join(sorted(available_presets.keys())))) else: print(_('Error: No stored presets.')) return 1 diff --git a/src/calibre/spell/dictionary.py b/src/calibre/spell/dictionary.py index 8d6f2a26df..04923b9f76 100644 --- a/src/calibre/spell/dictionary.py +++ b/src/calibre/spell/dictionary.py @@ -37,11 +37,10 @@ class UserDictionary: def __init__(self, **kwargs): self.name = kwargs['name'] self.is_active = kwargs['is_active'] - self.words = {(w, langcode) for w, langcode in kwargs['words']} + self.words = set(kwargs['words']) def serialize(self): - return {'name':self.name, 'is_active': self.is_active, 'words':[ - (w, l) for w, l in self.words]} + return {'name':self.name, 'is_active': self.is_active, 'words': list(self.words)} _builtins = _custom = None diff --git a/src/calibre/utils/bibtex.py b/src/calibre/utils/bibtex.py index ec50351418..c959a63c4b 100644 --- a/src/calibre/utils/bibtex.py +++ b/src/calibre/utils/bibtex.py @@ -2603,7 +2603,7 @@ class BibTeX: ''' Format authors for Bibtex compliance (get a list as input) ''' - return self.utf8ToBibtex(' and '.join(list(item))) + return self.utf8ToBibtex(' and '.join(item)) def stripUnmatchedSyntax(self, text, open_character, close_character): ''' diff --git a/src/calibre/utils/fonts/sfnt/subset.py b/src/calibre/utils/fonts/sfnt/subset.py index 843155631d..214ca7d2bd 100644 --- a/src/calibre/utils/fonts/sfnt/subset.py +++ b/src/calibre/utils/fonts/sfnt/subset.py @@ -254,7 +254,7 @@ def main(args): with open(iff, 'rb') as f: orig = f.read() - chars = list(chars.split(',')) + chars = chars.split(',') individual, ranges = set(), set() def not_single(c):