Skip to content

Commit

Permalink
[IMPR] use list comprehensions in several modules
Browse files Browse the repository at this point in the history
also use dict.values() if key is not used

Change-Id: I7113e50ee624fc346799fa04fcb2f50e395d6603
  • Loading branch information
xqt committed Jul 7, 2024
1 parent 4901a4a commit d897c7e
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 56 deletions.
10 changes: 4 additions & 6 deletions pywikibot/bot_choice.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,9 @@ def __init__(self, stop: bool = True) -> None:
@staticmethod
def formatted(text: str, options: Iterable[Option],
default: str | None = None) -> str:
"""
Create a text with the options formatted into it.
"""Create a text with the options formatted into it.
This static method is used by :py:meth:`pywikibot.input_choice`.
This static method is used by :meth:`pywikibot.input_choice`.
It calls :py:obj:`format` for all *options* to combine the
question for :py:meth:`pywikibot.input`.
Expand All @@ -84,9 +83,8 @@ def formatted(text: str, options: Iterable[Option],
:return: Text with the options formatted into it
"""
formatted_options = []
for option in options:
formatted_options.append(option.format(default=default))
formatted_options = [option.format(default=default)
for option in options]
# remove color highlights before fill function
text = f"{text} ({', '.join(formatted_options)})"
pattern = '<<[a-z]+>>'
Expand Down
7 changes: 3 additions & 4 deletions pywikibot/page/_collections.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Structures holding data for Wikibase entities."""
#
# (C) Pywikibot team, 2019-2022
# (C) Pywikibot team, 2019-2024
#
# Distributed under the terms of the MIT license.
#
Expand Down Expand Up @@ -471,14 +471,13 @@ def toJSON(self, diffto: dict | None = None) -> dict:
for dbname, sitelink in data.items():
if dbname not in diffto:
continue

diffto_link = diffto[dbname]
if diffto_link.get('title') == sitelink.get('title'):
# compare badges
tmp_badges = []
diffto_badges = diffto_link.get('badges', [])
badges = sitelink.get('badges', [])
for badge in set(diffto_badges) - set(badges):
tmp_badges.append('')
tmp_badges = [''] * len(set(diffto_badges) - set(badges))
for badge in set(badges) - set(diffto_badges):
tmp_badges.append(badge)
if tmp_badges:
Expand Down
2 changes: 1 addition & 1 deletion pywikibot/site/_apisite.py
Original file line number Diff line number Diff line change
Expand Up @@ -1651,7 +1651,7 @@ def getredirtarget(
if 'pages' not in result['query']:
# No "pages" element might indicate a circular redirect
# Check that a "to" link is also a "from" link in redirmap
for _from, _to in redirmap.items():
for _to in redirmap.values():
if _to['title'] in redirmap:
raise CircularRedirectError(page)

Expand Down
60 changes: 28 additions & 32 deletions scripts/dataextend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3190,12 +3190,11 @@ def findoccupations(self, html: str):
section = self.findbyre(
r'(?s)"description">\s*<span[^<>]*>(.*?)</span>', html)
if section:
result = []
texts = []
for subsection in section.split(' et '):
texts += self.findallbyre(r'(\w[\-\s\w&\']+)', subsection)
for text in texts[:8]:
result.append(self.findbyre(r'(.+)', text, 'occupation'))
result = [self.findbyre(r'(.+)', text, 'occupation')
for text in texts[:8]]
return result
return None

Expand Down Expand Up @@ -5261,24 +5260,20 @@ def findawards(self, html: str):
if section:
parts = self.findallbyre(r'(?s)(<tr><th.*?</tr>\s*<tr>.*?</tr>)',
section)
result = []
for part in parts:
if '[nominee]' not in part:
result.append(
self.findbyre(r'<th[^<>]*>(.*?)<', section, 'award'))
result = [self.findbyre(r'<th[^<>]*>(.*?)<', section, 'award')
for part in parts if '[nominee]' not in part]
return result
return None

def findnominations(self, html: str):
section = self.findbyre(r'(?s)<div id="awards".*?>(.*?)</table>', html)
if section:
parts = self.findallbyre(r'(?s)(<tr><th.*?</tr>\s*<tr>.*?</tr>)',
section)
result = []
for part in parts:
if '[nominee]' in part:
result.append(
self.findbyre(r'<th[^<>]*>(.*?)<', section, 'award'))
result = [self.findbyre(r'<th[^<>]*>(.*?)<', section, 'award')
for part in parts if '[nominee]' in part]
return result
return None

def findspouses(self, html: str):
return self.findallbyre(
Expand Down Expand Up @@ -6305,14 +6300,15 @@ def findworkfields(self, html: str):
if section:
preresults = self.findallbyre(r'(?s)<tr>(.*?)</tr>',
section.replace('&nbsp;', ' '))[:5]
results = []
for preresult in preresults:
if int(self.findbyre(r'">(\d+)</a>', preresult) or 0) > 5:
results.append(
self.findbyre(
r'(?s)"Mathematics Subject Classification">(.*?)<',
preresult, 'subject'))
return results
result = [
self.findbyre(
r'(?s)"Mathematics Subject Classification">(.*?)<',
preresult, 'subject')
for preresult in preresults
if int(self.findbyre(r'">(\d+)</a>', preresult) or 0) > 5
]
return result
return None

def findwebsite(self, html: str):
return self.findbyre(r'(?s)<td>Homepage:</td>\s*<td><a[^<>]*>(.*?)<',
Expand Down Expand Up @@ -8340,15 +8336,16 @@ def findresidences(self, html: str):
r'(?s)<b>Woon- en verblijfplaatsen</b>\s*</td>\s*</tr>\s*<tr>(.*?)</tbody>',
html)
if section:
result = []
subsections = self.findallbyre(r'(?s)(<tr.*?</tr>)', section)
for subsection in subsections:
result.append(
self.findbyre(
r'<td width="auto">([^<>]*)</td>', subsection, 'city')
or self.findbyre(
r'<span[^<>]*>(.*?)<', subsection, 'city'))
result = [
self.findbyre(
r'<td width="auto">([^<>]*)</td>', subsection, 'city')
or self.findbyre(
r'<span[^<>]*>(.*?)<', subsection, 'city')
for subsection in subsections
]
return result
return None

def findoccupations(self, html: str):
section = self.findbyre(
Expand Down Expand Up @@ -14882,10 +14879,9 @@ def findnationalities(self, html: str):

def findsources(self, html: str):
sources = self.getvalues('670', 'a', html)
result = []
for source in sources:
if source and ' by ' not in source and ' / ' not in source:
result.append(self.findbyre('(.*)', source, 'source'))
result = [self.findbyre('(.*)', source, 'source')
for source in sources
if source and ' by ' not in source and ' / ' not in source]
return result


Expand Down
5 changes: 2 additions & 3 deletions scripts/patrol.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,9 +354,8 @@ def match(self, page_title) -> bool:
if not self.linkedpages:
verbose_output('loading page links on ' + self.page_title)
p = pywikibot.Page(self.site, self.page_title)
linkedpages = []
for linkedpage in p.linkedPages():
linkedpages.append(linkedpage.title())
linkedpages = [linkedpage.title()
for linkedpage in p.linkedPages()]

self.linkedpages = linkedpages
verbose_output(f'Loaded {len(linkedpages)} page links')
Expand Down
4 changes: 2 additions & 2 deletions tests/site_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ def test_revdel_file(self):

fp2 = pywikibot.FilePage(site, 'File:T276726.png')
site.loadimageinfo(fp2, history=True)
for idx, v in fp2._file_revisions.items():
for v in fp2._file_revisions.values():
if v['timestamp'] in (ts1, ts2):
self.assertTrue(hasattr(v, 'commenthidden'))

Expand All @@ -753,7 +753,7 @@ def test_revdel_file(self):

fp3 = pywikibot.FilePage(site, 'File:T276726.png')
site.loadimageinfo(fp3, history=True)
for idx, v in fp3._file_revisions.items():
for v in fp3._file_revisions.values():
if v['timestamp'] in (ts1, ts2):
self.assertFalse(hasattr(v, 'commenthidden'))
self.assertFalse(hasattr(v, 'userhidden'))
Expand Down
9 changes: 4 additions & 5 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,11 +357,10 @@ def __init__(self, code, fam, user):
if self.family.name == 'wikisource':
extensions.append({'name': 'ProofreadPage'})
self._siteinfo._cache['extensions'] = (extensions, True)
aliases = []
for alias in ('PrefixIndex', ):
# TODO: Not all follow that scheme (e.g. "BrokenRedirects")
aliases.append(
{'realname': alias.capitalize(), 'aliases': [alias]})

# TODO: Not all follow that scheme (e.g. "BrokenRedirects")
aliases = [{'realname': alias.capitalize(), 'aliases': [alias]}
for alias in ('PrefixIndex', )]
self._siteinfo._cache['specialpagealiases'] = (aliases, True)
self._msgcache = {'*': 'dummy entry', 'hello': 'world'}

Expand Down
5 changes: 2 additions & 3 deletions tests/wikibase_edit_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,8 @@ def test_add_claim_with_qualifier(self):
item = pywikibot.PropertyPage(testsite, 'P115')
item.get()
if 'P115' in item.claims:
to_remove = []
for claim in item.claims['P115']:
to_remove.append({'id': claim.toJSON()['id'], 'remove': ''})
to_remove = [{'id': claim.toJSON()['id'], 'remove': ''}
for claim in item.claims['P115']]
item.editEntity({'claims': to_remove})

claim = pywikibot.page.Claim(
Expand Down

0 comments on commit d897c7e

Please sign in to comment.