jenkins-bot has submitted this change and it was merged.
Change subject: [FIX] W503 errors
......................................................................
[FIX] W503 errors
With a recent version of PEP8 (and thus flake8) binary operators (like
and) are not allowed at the start of a line and instead at the end of
the previous one. Double quotes in the affected lines too were changed.
Change-Id: I5d89afa1d7bd4711a80d8b6c831ee63afe440ef5
---
M generate_family_file.py
M pywikibot/data/api.py
M pywikibot/data/wikidataquery.py
M pywikibot/page.py
M pywikibot/pagegenerators.py
M pywikibot/site.py
M pywikibot/userinterfaces/win32_unicode.py
M scripts/archivebot.py
M scripts/category_redirect.py
M scripts/commonscat.py
M scripts/interwiki.py
M scripts/solve_disambiguation.py
M scripts/transferbot.py
M scripts/unlink.py
M tests/__init__.py
M tests/aspects.py
M tests/script_tests.py
M tests/site_tests.py
18 files changed, 93 insertions(+), 100 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/generate_family_file.py b/generate_family_file.py
index 28af939..fa4619b 100644
--- a/generate_family_file.py
+++ b/generate_family_file.py
@@ -143,8 +143,8 @@
print(wiki['prefix'], wiki['url'])
do_langs = raw_input("Which languages do you want: ")
self.langs = [wiki for wiki in self.langs
- if wiki['prefix'] in do_langs
- or wiki['url'] == w.iwpath]
+ if wiki['prefix'] in do_langs or
+ wiki['url'] == w.iwpath]
else:
self.langs = [wiki for wiki in self.langs
if wiki[u'url'] == w.iwpath]
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index a84b08c..4433982 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -332,8 +332,8 @@
for mod in module_batch]
else:
params['modules'] = [mod for mod in module_batch
- if mod not in self._query_modules
- and mod not in self.root_modules]
+ if mod not in self._query_modules and
+ mod not in self.root_modules]
params['querymodules'] = [mod for mod in module_batch
if mod in self._query_modules]
@@ -818,8 +818,8 @@
self["assert"] = 'user' # make sure user is logged in
if (self.site.protocol() == 'http' and (config.use_SSL_always or (
- self.action == 'login' and config.use_SSL_onlogin))
- and self.site.family.name in config.available_ssl_project):
+ self.action == 'login' and config.use_SSL_onlogin)) and
+ self.site.family.name in config.available_ssl_project):
self.site = EnableSSLSiteWrapper(self.site)
@classmethod
@@ -1031,9 +1031,9 @@
def __str__(self):
"""Return a string representation."""
- return unquote(self.site.scriptpath()
- + "/api.php?"
- + self._http_param_string())
+ return unquote(self.site.scriptpath() +
+ '/api.php?' +
+ self._http_param_string())
def __repr__(self):
"""Return internal representation."""
@@ -1267,10 +1267,10 @@
else:
self.site._userinfo = result['query']['userinfo']
status = self.site._loginstatus # save previous login status
- if (("error" in result
- and result["error"]["code"].endswith("limit"))
- or (status >= 0
- and self.site._userinfo['name'] != self.site._username[status])):
+ if (('error' in result and
+ result['error']['code'].endswith('limit')) or
+ (status >= 0 and
+ self.site._userinfo['name'] != self.site._username[status])):
# user is no longer logged in (session expired?)
# reset userinfo, then make user log in again
del self.site._userinfo
diff --git a/pywikibot/data/wikidataquery.py b/pywikibot/data/wikidataquery.py
index 5ad6bed..b9fe073 100644
--- a/pywikibot/data/wikidataquery.py
+++ b/pywikibot/data/wikidataquery.py
@@ -316,8 +316,8 @@
if not self.isOrContainsOnlyTypes(item, [int, ItemPage]):
raise TypeError("The item paramter must contain or be integer IDs "
"or page.ItemPages")
- elif (not self.isOrContainsOnlyTypes(forward, [int, PropertyPage])
- or not self.isOrContainsOnlyTypes(reverse, [int, PropertyPage])):
+ elif (not self.isOrContainsOnlyTypes(forward, [int, PropertyPage]) or
+ not self.isOrContainsOnlyTypes(reverse, [int, PropertyPage])):
raise TypeError("The forward and reverse parameters must contain "
"or be integer IDs or page.PropertyPages")
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 1befe68..1741107 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -218,8 +218,8 @@
target_family = config.family
if forceInterwiki or \
(allowInterwiki and
- (self.site.family.name != target_family
- or self.site.code != target_code)):
+ (self.site.family.name != target_family or
+ self.site.code != target_code)):
if self.site.family.name != target_family \
and self.site.family.name != self.site.code:
title = u'%s:%s:%s' % (self.site.family.name,
@@ -1559,8 +1559,8 @@
"""
if hasattr(self, "_deletedRevs"):
if timestamp in self._deletedRevs and (
- (not retrieveText)
- or "content" in self._deletedRevs[timestamp]):
+ (not retrieveText) or
+ 'content' in self._deletedRevs[timestamp]):
return self._deletedRevs[timestamp]
for item in self.site.deletedrevs(self, start=timestamp,
get_text=retrieveText, total=1):
@@ -4521,13 +4521,13 @@
# * with 'relative' URLs. Forbid them explicitly.
if u'.' in t and (
- t == u'.' or t == u'..'
- or t.startswith(u"./")
- or t.startswith(u"../")
- or u"/./" in t
- or u"/../" in t
- or t.endswith(u"/.")
- or t.endswith(u"/..")
+ t == u'.' or t == u'..' or
+ t.startswith(u'./') or
+ t.startswith(u'../') or
+ u'/./' in t or
+ u'/../' in t or
+ t.endswith(u'/.') or
+ t.endswith(u'/..')
):
raise pywikibot.InvalidTitle(
u"(contains . / combinations): '%s'"
diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index 9a66176..a87a05a 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -469,8 +469,7 @@
if not fileLinksPageTitle:
fileLinksPageTitle = i18n.input(
'pywikibot-enter-file-links-processing')
- if fileLinksPageTitle.startswith(self.site.namespace(6)
- + ":"):
+ if fileLinksPageTitle.startswith(self.site.namespace(6) + ':'):
fileLinksPage = pywikibot.FilePage(self.site,
fileLinksPageTitle)
else:
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 80c627c..ffedbaf 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -455,8 +455,8 @@
# int(None) raises TypeError; however, bool needs special handling.
result = [NotImplemented if isinstance(ns, bool) else
Namespace.lookup_name(ns, namespaces)
- if isinstance(ns, basestring)
- and not ns.lstrip('-').isdigit() else
+ if isinstance(ns, basestring) and
+ not ns.lstrip('-').isdigit() else
namespaces[int(ns)] if int(ns) in namespaces
else None
for ns in identifiers]
@@ -1702,10 +1702,9 @@
- blockinfo: present if user is blocked (dict)
"""
- if (not hasattr(self, "_userinfo")
- or "rights" not in self._userinfo
- or self._userinfo['name']
- != self._username["sysop" in self._userinfo["groups"]]):
+ if (not hasattr(self, '_userinfo') or
+ 'rights' not in self._userinfo or
+ self._userinfo['name'] != self._username['sysop' in self._userinfo['groups']]):
uirequest = api.Request(
site=self,
action="query",
@@ -1788,8 +1787,8 @@
@rtype: C{set} of L{Namespace}
"""
# TODO: Integrate into _userinfo
- if (force or not hasattr(self, "_useroptions")
- or self.user() != self._useroptions['_name']):
+ if (force or not hasattr(self, '_useroptions') or
+ self.user() != self._useroptions['_name']):
uirequest = api.Request(
site=self,
action="query",
@@ -1806,8 +1805,8 @@
self._useroptions['_name'] = (
None if 'anon' in uidata['query']['userinfo'] else
uidata['query']['userinfo']['name'])
- return set(ns for ns in self.namespaces().values() if ns.id >= 0
- and self._useroptions['searchNs{0}'.format(ns.id)] in ['1', True])
+ return set(ns for ns in self.namespaces().values() if ns.id >= 0 and
+ self._useroptions['searchNs{0}'.format(ns.id)] in ['1', True])
def assert_valid_iter_params(self, msg_prefix, start, end, reverse):
"""Validate iterating API parameters."""
@@ -3337,13 +3336,12 @@
if prefix:
apgen.request["gapprefix"] = prefix
if filterredir is not None:
- apgen.request["gapfilterredir"] = (filterredir
- and "redirects"
- or "nonredirects")
+ apgen.request['gapfilterredir'] = ('redirects' if filterredir else
+ 'nonredirects')
if filterlanglinks is not None:
- apgen.request["gapfilterlanglinks"] = (filterlanglinks
- and "withlanglinks"
- or "withoutlanglinks")
+ apgen.request['gapfilterlanglinks'] = ('withlanglinks'
+ if filterlanglinks else
+ 'withoutlanglinks')
if isinstance(minsize, int):
apgen.request["gapminsize"] = str(minsize)
if isinstance(maxsize, int):
@@ -3602,8 +3600,8 @@
"""
iuargs = dict(giutitle=image.title(withSection=False))
if filterredir is not None:
- iuargs["giufilterredir"] = (filterredir and "redirects"
- or "nonredirects")
+ iuargs['giufilterredir'] = ('redirects' if filterredir else
+ 'nonredirects')
iugen = self._generator(api.PageGenerator, type_arg="imageusage",
namespaces=namespaces, step=step,
total=total, g_content=content, **iuargs)
@@ -4893,8 +4891,8 @@
break
else: # not chunked upload
file_contents = f.read()
- filetype = (mimetypes.guess_type(source_filename)[0]
- or 'application/octet-stream')
+ filetype = (mimetypes.guess_type(source_filename)[0] or
+ 'application/octet-stream')
additional_parameters = {
'mime_params': {
'file': (file_contents,
diff --git a/pywikibot/userinterfaces/win32_unicode.py b/pywikibot/userinterfaces/win32_unicode.py
index 64016f7..3e77812 100755
--- a/pywikibot/userinterfaces/win32_unicode.py
+++ b/pywikibot/userinterfaces/win32_unicode.py
@@ -83,8 +83,8 @@
def not_a_console(handle):
if handle == INVALID_HANDLE_VALUE or handle is None:
return True
- return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
- or GetConsoleMode(handle, byref(DWORD())) == 0)
+ return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
+ GetConsoleMode(handle, byref(DWORD())) == 0)
old_stdin_fileno = None
old_stdout_fileno = None
diff --git a/scripts/archivebot.py b/scripts/archivebot.py
index 993c454..e2508da 100644
--- a/scripts/archivebot.py
+++ b/scripts/archivebot.py
@@ -422,8 +422,8 @@
self.attributes[attr] = [value, out]
def saveables(self):
- return [a for a in self.attributes if self.attributes[a][1]
- and a != 'maxage']
+ return [a for a in self.attributes if self.attributes[a][1] and
+ a != 'maxage']
def attr2text(self):
return '{{%s\n%s\n}}' \
diff --git a/scripts/category_redirect.py b/scripts/category_redirect.py
index af0aca3..c68c8c7 100755
--- a/scripts/category_redirect.py
+++ b/scripts/category_redirect.py
@@ -437,12 +437,12 @@
newredirs.sort()
comment = i18n.twtranslate(self.site.code, self.maint_comment)
self.log_page.text = (u"\n== %i-%02i-%02iT%02i:%02i:%02iZ ==\n"
- % time.gmtime()[:6]
- + u"\n".join(self.log_text)
- + u"\n* New redirects since last report:\n"
- + u"\n".join(newredirs)
- + u"\n" + u"\n".join(self.problems)
- + u"\n" + self.get_log_text())
+ % time.gmtime()[:6] +
+ u'\n'.join(self.log_text) +
+ u'\n* New redirects since last report:\n' +
+ u'\n'.join(newredirs) +
+ u'\n' + u'\n'.join(self.problems) +
+ u'\n' + self.get_log_text())
self.log_page.save(comment)
if self.edit_requests:
edit_request_page.text = (self.edit_request_text
diff --git a/scripts/commonscat.py b/scripts/commonscat.py
index b078987..957983c 100755
--- a/scripts/commonscat.py
+++ b/scripts/commonscat.py
@@ -387,8 +387,8 @@
ipage = pywikibot.page.Page(ipageLink)
pywikibot.log("Looking for template on %s" % (ipage.title()))
try:
- if(not ipage.exists() or ipage.isRedirectPage()
- or ipage.isDisambig()):
+ if (not ipage.exists() or ipage.isRedirectPage() or
+ ipage.isDisambig()):
continue
commonscatLink = self.getCommonscatLink(ipage)
if not commonscatLink:
diff --git a/scripts/interwiki.py b/scripts/interwiki.py
index f17bc0c..becd5de 100755
--- a/scripts/interwiki.py
+++ b/scripts/interwiki.py
@@ -1726,8 +1726,8 @@
for (site, page) in new.items():
# edit restriction for some templates on zh-wiki where
# interlanguage keys are included by /doc subpage
- smallWikiAllowed = not (page.site.sitename() == 'wikipedia:zh'
- and page.namespace() == 10 and
+ smallWikiAllowed = not (page.site.sitename() == 'wikipedia:zh' and
+ page.namespace() == 10 and
u'Country data' in page.title(withNamespace=False))
# edit restriction on is-wiki
# https://is.wikipedia.org/wiki/Wikipediaspjall:V%C3%A9lmenni
diff --git a/scripts/solve_disambiguation.py b/scripts/solve_disambiguation.py
index ed1c814..fad491e 100644
--- a/scripts/solve_disambiguation.py
+++ b/scripts/solve_disambiguation.py
@@ -660,12 +660,10 @@
if not self.always:
# at the beginning of the link, start red color.
# at the end of the link, reset the color to default
- pywikibot.output(text[max(0, m.start() - context):
- m.start()]
- + '\03{lightred}'
- + text[m.start():m.end()]
- + '\03{default}'
- + text[m.end():m.end() + context])
+ pywikibot.output(
+ text[max(0, m.start() - context):m.start()] +
+ '\03{lightred}' + text[m.start():m.end()] +
+ '\03{default}' + text[m.end():m.end() + context])
options = ['#', 'r#', '[s]kip link', '[e]dit page',
'[n]ext page', '[u]nlink', '[q]uit']
if self.dn_template_str:
@@ -804,8 +802,8 @@
new_page_title = self.alternatives[choice]
repPl = pywikibot.Page(pywikibot.Link(new_page_title,
disambPage.site))
- if (new_page_title[0].isupper()
- or link_text[0].isupper()):
+ if (new_page_title[0].isupper() or
+ link_text[0].isupper()):
new_page_title = repPl.title()
else:
new_page_title = repPl.title()
@@ -817,8 +815,8 @@
newlink = "[[%s%s]]%s" % (new_page_title,
section,
trailing_chars)
- elif replaceit or (new_page_title == link_text
- and not section):
+ elif replaceit or (new_page_title == link_text and
+ not section):
newlink = "[[%s]]" % new_page_title
# check if we can create a link with trailing characters
# instead of a pipelink
@@ -856,8 +854,8 @@
def findAlternatives(self, disambPage):
if disambPage.isRedirectPage() and not self.primary:
- if (disambPage.site.lang in self.primary_redir_template
- and self.primary_redir_template[disambPage.site.lang]
+ if (disambPage.site.lang in self.primary_redir_template and
+ self.primary_redir_template[disambPage.site.lang]
in disambPage.templates(get_redirect=True)):
baseTerm = disambPage.title()
for template in disambPage.templatesWithParams(
diff --git a/scripts/transferbot.py b/scripts/transferbot.py
index 599bc91..8b9cbcf 100644
--- a/scripts/transferbot.py
+++ b/scripts/transferbot.py
@@ -134,8 +134,7 @@
for page in gen:
summary = "Moved page from %s" % page.title(asLink=True)
targetpage = pywikibot.Page(tosite, prefix + page.title())
- edithistpage = pywikibot.Page(tosite, prefix + page.title()
- + "/edithistory")
+ edithistpage = pywikibot.Page(tosite, prefix + page.title() + '/edithistory')
if targetpage.exists() and not overwrite:
pywikibot.output(
diff --git a/scripts/unlink.py b/scripts/unlink.py
index de05fdd..403d626 100755
--- a/scripts/unlink.py
+++ b/scripts/unlink.py
@@ -99,9 +99,9 @@
choice = 'a'
else:
pywikibot.output(
- text[max(0, match.start() - context):match.start()]
- + '\03{lightred}' + text[match.start():match.end()]
- + '\03{default}' + text[match.end():match.end() + context])
+ text[max(0, match.start() - context):match.start()] +
+ '\03{lightred}' + text[match.start():match.end()] +
+ '\03{default}' + text[match.end():match.end() + context])
choice = pywikibot.input_choice(
u'\nWhat shall be done with this link?\n',
[('unlink', 'u'), ('skip', 's'), ('edit', 'e'),
diff --git a/tests/__init__.py b/tests/__init__.py
index 0f8012a..556162f 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -102,13 +102,13 @@
"""List tests which are to be executed."""
dir_list = os.listdir(_tests_dir)
all_test_list = [name[0:-9] for name in dir_list # strip '_tests.py'
- if name.endswith('_tests.py')
- and not name.startswith('_')] # skip __init__.py and _*
+ if name.endswith('_tests.py') and
+ not name.startswith('_')] # skip __init__.py and _*
unknown_test_modules = [name
for name in all_test_list
- if name not in library_test_modules
- and name not in script_test_modules]
+ if name not in library_test_modules and
+ name not in script_test_modules]
return unknown_test_modules
diff --git a/tests/aspects.py b/tests/aspects.py
index 8147a70..250ffb2 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -687,9 +687,9 @@
if 'family' in dct or 'code' in dct:
dct['site'] = True
- if (('sites' not in dct or not len(dct['sites']))
- and 'family' in dct
- and 'code' in dct and dct['code'] != '*'):
+ if (('sites' not in dct or not len(dct['sites'])) and
+ 'family' in dct and
+ 'code' in dct and dct['code'] != '*'):
# Add entry to self.sites
dct['sites'] = {
str(dct['family'] + ':' + dct['code']): {
diff --git a/tests/script_tests.py b/tests/script_tests.py
index 6810a00..aea9dcc 100644
--- a/tests/script_tests.py
+++ b/tests/script_tests.py
@@ -68,9 +68,9 @@
script_list = (['login'] +
[name[0:-3] for name in os.listdir(scripts_path) # strip '.py'
- if name.endswith('.py')
- and not name.startswith('_') # skip __init__.py and _*
- and name != 'login.py' # this is moved to be first
+ if name.endswith('.py') and
+ not name.startswith('_') and # skip __init__.py and _*
+ name != 'login.py' # this is moved to be first
]
)
@@ -181,17 +181,17 @@
tests = (['test__login_help'] +
['test_' + name + '_help'
for name in sorted(script_list)
- if name != 'login'
- and name not in deadlock_script_list] +
+ if name != 'login' and
+ name not in deadlock_script_list] +
['test__login_simulate'])
tests += ['test_' + name + '_simulate'
for name in sorted(script_list)
- if name != 'login'
- and name not in deadlock_script_list
- and name not in failed_dep_script_list
- and name not in unrunnable_script_list
- and (enable_autorun_tests or name not in auto_run_script_list)]
+ if name != 'login' and
+ name not in deadlock_script_list and
+ name not in failed_dep_script_list and
+ name not in unrunnable_script_list and
+ (enable_autorun_tests or name not in auto_run_script_list)]
test_list = ['tests.script_tests.TestScript.' + name
for name in tests]
@@ -285,8 +285,8 @@
# But also complain if there is any stdout
# but ignore shell.py emiting its '>>> ' prompt.
if ((script_name == 'shell' and
- set(result['stdout']).issubset(set('> \n')))
- or result['stdout'] == ''):
+ set(result['stdout']).issubset(set('> \n'))) or
+ result['stdout'] == ''):
result['stdout'] = None
self.assertIsNone(result['stdout'])
diff --git a/tests/site_tests.py b/tests/site_tests.py
index b62bba7..b3ac597 100644
--- a/tests/site_tests.py
+++ b/tests/site_tests.py
@@ -971,8 +971,7 @@
self.assertLessEqual(len(uc), 10)
self.assertTrue(all(isinstance(contrib, dict)
for contrib in uc))
- self.assertTrue(all("user" in contrib
- and contrib["user"] == mysite.user()
+ self.assertTrue(all('user' in contrib and contrib['user'] == mysite.user()
for contrib in uc))
for contrib in mysite.usercontribs(userprefix="John", total=5):
self.assertIsInstance(contrib, dict)
--
To view, visit https://gerrit.wikimedia.org/r/190753
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I5d89afa1d7bd4711a80d8b6c831ee63afe440ef5
Gerrit-PatchSet: 2
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Minor documentation fixes
......................................................................
Minor documentation fixes
Change-Id: Idde50d76be2cbf05a6075c9ff39fdbb5a029bee4
---
M pywikibot/userinterfaces/win32_unicode.py
1 file changed, 3 insertions(+), 3 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/userinterfaces/win32_unicode.py b/pywikibot/userinterfaces/win32_unicode.py
index 9e4dded..64016f7 100755
--- a/pywikibot/userinterfaces/win32_unicode.py
+++ b/pywikibot/userinterfaces/win32_unicode.py
@@ -1,7 +1,7 @@
"""Stdout, stderr and argv support for unicode."""
##############################################
# Support for unicode in windows cmd.exe
-# Posted on Stack Overflow [1], available under CC-BY-SA [2]
+# Posted on Stack Overflow [1], available under CC-BY-SA 3.0 [2]
#
# Question: "Windows cmd encoding change causes Python crash" [3] by Alex [4],
# Answered [5] by David-Sarah Hopwood [6].
@@ -15,8 +15,8 @@
#
################################################
#
-# stdin support added by Merlijn van Deen <valhallasw(a)gmail.com>, march 2012
-# Licensed under both CC-BY-SA as the MIT license.
+# stdin support added by Merlijn van Deen <valhallasw(a)gmail.com>, March 2012
+# Licensed under both CC-BY-SA and the MIT license.
#
################################################
from __future__ import print_function
--
To view, visit https://gerrit.wikimedia.org/r/190716
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Idde50d76be2cbf05a6075c9ff39fdbb5a029bee4
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [FEAT] Site: blockuser's expiry supports datetime and False
......................................................................
[FEAT] Site: blockuser's expiry supports datetime and False
As it already support timestamps the addition of normal datetimes is not
that far fetched. It also supports 'False' as an alias for 'never' so
scripts are independent of the API and only pywikibot needs to use the
actual API value.
This also adds the documentation for this function.
Change-Id: I352d155cea0d251f35d27e887bbc84e6ee83d549
---
M pywikibot/site.py
1 file changed, 33 insertions(+), 0 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index c4cd53d..626a8ee 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -4396,8 +4396,41 @@
@must_be(group='sysop')
def blockuser(self, user, expiry, reason, anononly=True, nocreate=True,
autoblock=True, noemail=False, reblock=False):
+ """
+ Block a user for certain amount of time and for a certain reason.
+ @param user: The username/IP to be blocked without a namespace.
+ @type user: User
+ @param expiry: The length or date/time when the block expires. If
+ 'never', 'infinite', 'indefinite' it never does. If the value is
+ given as a basestring it's parsed by php's strtotime function:
+ http://php.net/manual/en/function.strtotime.php
+ The relative format is described there:
+ http://php.net/manual/en/datetime.formats.relative.php
+ It is recommended to not use a basestring if possible to be
+ independent of the API.
+ @type expiry: Timestamp/datetime (absolute),
+ basestring (relative/absolute) or False ('never')
+ @param reason: The reason for the block.
+ @type reason: basestring
+ @param anononly: Disable anonymous edits for this IP.
+ @type anononly: boolean
+ @param nocreate: Prevent account creation.
+ @type nocreate: boolean
+ @param autoblock: Automatically block the last used IP address and all
+ subsequent IP addresses from which this account logs in.
+ @type autoblock: boolean
+ @param noemail: Prevent user from sending email through the wiki.
+ @type noemail: boolean
+ @param reblock: If the user is already blocked, overwrite the existing
+ block.
+ @type reblock: boolean
+ @return: The data retrieved from the API request.
+ @rtype: dict
+ """
token = self.tokens['block']
+ if expiry is False:
+ expiry = 'never'
req = api.Request(site=self, action='block', user=user.username,
expiry=expiry, reason=reason, token=token)
if anononly:
--
To view, visit https://gerrit.wikimedia.org/r/181082
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I352d155cea0d251f35d27e887bbc84e6ee83d549
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: tools.py: introduce class DotReadableDict(), super of Revision() and FileInfo()
......................................................................
tools.py: introduce class DotReadableDict(), super of Revision() and FileInfo()
Parent class of Page.Revision() and Page.FileInfo().
Provide:
- __getitem__()
- __unicode__()
-__repr__().
Change-Id: I45877492693837da4f53f11f9869a52dea25c3b0
---
M pywikibot/page.py
M pywikibot/tools.py
2 files changed, 38 insertions(+), 38 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index bb1f515..1befe68 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -48,6 +48,7 @@
SiteDefinitionError
)
from pywikibot.tools import (
+ UnicodeMixin, DotReadableDict,
ComparableMixin, deprecated, deprecate_arg, deprecated_args,
remove_last_args, _NotImplementedWarning,
OrderedDict, Counter,
@@ -64,7 +65,7 @@
# Note: Link objects (defined later on) represent a wiki-page's title, while
# Page objects (defined here) represent the page itself, including its contents.
-class BasePage(pywikibot.UnicodeMixin, ComparableMixin):
+class BasePage(UnicodeMixin, ComparableMixin):
"""BasePage: Base object for a MediaWiki page.
@@ -4210,7 +4211,7 @@
}
-class Revision(pywikibot.UnicodeMixin):
+class Revision(DotReadableDict):
"""A structure holding information about a single revision of a Page."""
@@ -4268,29 +4269,8 @@
return Revision.FullHistEntry(self.revid, self.timestamp, self.user,
self.text, self.rollbacktoken)
- def __getitem__(self, key):
- """Give access to Revision class values by key.
- Revision class may also give access to its values by keys
- e.g. revid parameter may be assigned by revision['revid']
- as well as revision.revid. This makes formatting strings with
- % operator easier.
-
- """
- return getattr(self, key)
-
- def __unicode__(self):
- """Return string representation."""
- _content = u', '.join(
- u'{0}: {1}'.format(k, v) for k, v in self.__dict__.items())
- return u'{{{0}}}'.format(_content)
-
- def __repr__(self):
- """Return a more complete string representation."""
- return self.__dict__.__repr__()
-
-
-class FileInfo(pywikibot.UnicodeMixin):
+class FileInfo(DotReadableDict):
"""A structure holding imageinfo of latest rev. of FilePage.
@@ -4316,23 +4296,9 @@
self.__dict__.update(file_revision)
self.timestamp = pywikibot.Timestamp.fromISOformat(self.timestamp)
- def __getitem__(self, key):
- """Access attributes also with dict.like keys."""
- return getattr(self, key)
-
def __eq__(self, other):
"""Test if two File_info objects are equal."""
return self.__dict__ == other.__dict__
-
- def __unicode__(self):
- """Return string representation."""
- _content = u', '.join(
- u'{0}: {1}'.format(k, v) for k, v in self.__dict__.items())
- return u'{{{0}}}'.format(_content)
-
- def __repr__(self):
- """Return a more complete string representation."""
- return self.__dict__.__repr__()
class Link(ComparableMixin):
diff --git a/pywikibot/tools.py b/pywikibot/tools.py
index dd5ec2c..cb19499 100644
--- a/pywikibot/tools.py
+++ b/pywikibot/tools.py
@@ -136,6 +136,40 @@
return other != self._cmpkey()
+class DotReadableDict(UnicodeMixin):
+
+ """Parent class of Revision() and FileInfo().
+
+ Provide:
+ - __getitem__(), __unicode__() and __repr__().
+
+ """
+
+ def __getitem__(self, key):
+ """Give access to class values by key.
+
+ Revision class may also give access to its values by keys
+ e.g. revid parameter may be assigned by revision['revid']
+ as well as revision.revid. This makes formatting strings with
+ % operator easier.
+
+ """
+ return getattr(self, key)
+
+ def __unicode__(self):
+ """Return string representation."""
+ if sys.version_info[0] > 2:
+ return repr(self.__dict__)
+ else:
+ _content = u', '.join(
+ u'{0}: {1}'.format(k, v) for k, v in self.__dict__.items())
+ return u'{{{0}}}'.format(_content)
+
+ def __repr__(self):
+ """Return a more complete string representation."""
+ return repr(self.__dict___)
+
+
def concat_options(message, line_length, options):
"""Concatenate options."""
indent = len(message) + 2
--
To view, visit https://gerrit.wikimedia.org/r/190563
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I45877492693837da4f53f11f9869a52dea25c3b0
Gerrit-PatchSet: 2
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: Ricordisamoa <ricordisamoa(a)openmailbox.org>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>