jenkins-bot has submitted this change and it was merged.
Change subject: pep8ify site.py,
......................................................................
pep8ify site.py,
remove obsolete "return None"
Change-Id: Ia3233f6647b394be16de888c548e84dadc1d1998
---
M pywikibot/site.py
1 file changed, 154 insertions(+), 94 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 933eb14..18416c1 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -63,7 +63,8 @@
for key, value in cls.__dict__.iteritems():
if key == key.upper() and value == search_value:
return key
- raise KeyError("Value %r could not be found in this enum" % search_value)
+ raise KeyError("Value %r could not be found in this enum"
+ % search_value)
def Family(fam=None, fatal=True):
@@ -151,7 +152,8 @@
if sysop:
sysop = sysop[0].upper() + sysop[1:]
self._username = [user, sysop]
- self.use_hard_category_redirects = self.code in self.family.use_hard_category_redirects
+ self.use_hard_category_redirects = (
+ self.code in self.family.use_hard_category_redirects)
# following are for use with lock_page and unlock_page methods
self._pagemutex = threading.Lock()
@@ -207,7 +209,6 @@
return self._username[True]
elif self.logged_in(False):
return self._username[False]
- return None
def username(self, sysop=False):
return self._username[sysop]
@@ -272,7 +273,6 @@
if namespace.lower() in [name.lower()
for name in self.namespaces()[ns]]:
return ns
- return None
getNamespaceIndex = ns_index # for backwards-compatibility
@@ -351,7 +351,8 @@
"""Return Category in which disambig pages are listed."""
try:
- name = self.namespace(14) + ':' + self.family.disambcatname[self.code]
+ name = '%s:%s' % (self.namespace(14),
+ self.family.disambcatname[self.code])
except KeyError:
raise Error(u"No disambiguation category name found for %(site)s"
% {'site': self})
@@ -395,12 +396,17 @@
"""Return True iff title1 and title2 identify the same wiki page."""
# title1 and title2 may be unequal but still identify the same page,
# if they use different aliases for the same namespace
+
def valid_namespace(text, number):
- """Return True iff text is a valid alias for namespace with given number."""
+ """Return True if text is a valid alias for namespace with given
+ number.
+
+ """
for alias in self.namespace(number, all=True):
if text.lower() == alias.lower():
return True
return False
+
if title1 == title2:
return True
# determine whether titles contain namespace prefixes
@@ -469,7 +475,8 @@
# TODO: is this even needed? No family in the framework has this
# dictionary defined!
if self.lang in self.family.interwiki_putfirst_doubled:
- if len(list_of_links) >= self.family.interwiki_putfirst_doubled[self.lang][0]:
+ if (len(list_of_links) >=
+ self.family.interwiki_putfirst_doubled[self.lang][0]):
links2 = [lang.language() for lang in list_of_links]
result = []
for lang in self.family.interwiki_putfirst_doubled[self.lang][1]:
@@ -866,7 +873,8 @@
if hasattr(self, "_userinfo"):
del self._userinfo
self.getuserinfo()
- if self.userinfo['name'] == self._username[sysop] and self.logged_in(sysop):
+ if self.userinfo['name'] == self._username[sysop] and \
+ self.logged_in(sysop):
return
loginMan = api.LoginManager(site=self, sysop=sysop,
user=self._username[sysop])
@@ -875,7 +883,8 @@
if hasattr(self, "_userinfo"):
del self._userinfo
self.getuserinfo()
- self._loginstatus = LoginStatus.AS_SYSOP if sysop else LoginStatus.AS_USER
+ self._loginstatus = (LoginStatus.AS_SYSOP
+ if sysop else LoginStatus.AS_USER)
else:
self._loginstatus = LoginStatus.NOT_LOGGED_IN # failure
if not hasattr(self, "_siteinfo"):
@@ -1151,7 +1160,8 @@
self._getsiteinfo()
if self._extensions is None:
if isinstance(unknown, type) and issubclass(unknown, Exception):
- raise unknown("Feature 'hasExtension' only available in MW 1.14+")
+ raise unknown(
+ "Feature 'hasExtension' only available in MW 1.14+")
else:
return unknown
for ext in self._extensions:
@@ -1261,8 +1271,6 @@
m = re.match(r"^MediaWiki ([0-9]+)\.([0-9]+)(.*)$", versionstring)
if m:
return (int(m.group(1)), int(m.group(2)), m.group(3))
- else:
- return None
def loadpageinfo(self, page):
"""Load page info from api and save in page attributes"""
@@ -1281,7 +1289,7 @@
def loadcoordinfo(self, page):
"""Load [[mw:Extension:GeoData]] info"""
- #prop=coordinates&titles=Wikimedia Foundation&format=jsonfm&coprop=type|name|dim|country|region&coprimary=all
+ # prop=coordinates&titles=Wikimedia Foundation&format=jsonfm&coprop=type|name|dim|country|region&coprimary=all
title = page.title(withSection=False)
query = self._generator(api.PropertyGenerator,
type_arg="coordinates",
@@ -1334,7 +1342,8 @@
u"loadimageinfo: Query on %s returned data on '%s'"
% (page, pageitem['title']))
api.update_page(page, pageitem)
- return pageitem['imageinfo'] if history else pageitem['imageinfo'][0]
+ return (pageitem['imageinfo']
+ if history else pageitem['imageinfo'][0])
def page_exists(self, page):
"""Return True if and only if page is an existing page on site."""
@@ -1461,8 +1470,8 @@
break
else:
pywikibot.warning(
- u"preloadpages: Query returned unexpected title '%s'"
- % pagedata['title'])
+ u"preloadpages: Query returned unexpected title"
+ u"'%s'" % pagedata['title'])
continue
except KeyError:
pywikibot.debug(u"No 'title' in %s" % pagedata, _logger)
@@ -1518,7 +1527,8 @@
bltitle = page.title(withSection=False).encode(self.encoding())
blargs = {"gbltitle": bltitle}
if filterRedirects is not None:
- blargs["gblfilterredir"] = filterRedirects and "redirects" or "nonredirects"
+ blargs["gblfilterredir"] = (filterRedirects and "redirects" or
+ "nonredirects")
blgen = self._generator(api.PageGenerator, type_arg="backlinks",
namespaces=namespaces, step=step, total=total,
g_content=content, **blargs)
@@ -1565,9 +1575,11 @@
(default False)
"""
- eiargs = {"geititle": page.title(withSection=False).encode(self.encoding())}
+ eiargs = {"geititle":
+ page.title(withSection=False).encode(self.encoding())}
if filterRedirects is not None:
- eiargs["geifilterredir"] = filterRedirects and "redirects" or "nonredirects"
+ eiargs["geifilterredir"] = (filterRedirects and "redirects" or
+ "nonredirects")
eigen = self._generator(api.PageGenerator, type_arg="embeddedin",
namespaces=namespaces, step=step, total=total,
g_content=content, **eiargs)
@@ -1635,7 +1647,8 @@
if hasattr(page, "_pageid"):
clargs['pageids'] = str(page._pageid)
else:
- clargs['titles'] = page.title(withSection=False).encode(self.encoding())
+ clargs['titles'] = page.title(
+ withSection=False).encode(self.encoding())
clgen = self._generator(api.CategoryPageGenerator,
type_arg="categories", step=step, total=total,
g_content=content, **clargs)
@@ -1736,23 +1749,23 @@
if starttime and sortby == "timestamp":
cmargs["gcmstart"] = str(starttime)
elif starttime:
- raise ValueError(
- "categorymembers: invalid combination of 'sortby' and 'starttime'")
+ raise ValueError("categorymembers: "
+ "invalid combination of 'sortby' and 'starttime'")
if endtime and sortby == "timestamp":
cmargs["gcmend"] = str(endtime)
elif endtime:
- raise ValueError(
- "categorymembers: invalid combination of 'sortby' and 'endtime'")
+ raise ValueError("categorymembers: "
+ "invalid combination of 'sortby' and 'endtime'")
if startsort and sortby != "timestamp":
cmargs["gcmstartsortkey"] = startsort
elif startsort:
- raise ValueError(
- "categorymembers: invalid combination of 'sortby' and 'startsort'")
+ raise ValueError("categorymembers: "
+ "invalid combination of 'sortby' and 'startsort'")
if endsort and sortby != "timestamp":
cmargs["gcmendsortkey"] = endsort
elif endsort:
- raise ValueError(
- "categorymembers: invalid combination of 'sortby' and 'endsort'")
+ raise ValueError("categorymembers: "
+ "invalid combination of 'sortby' and 'endsort'")
cmgen = self._generator(api.PageGenerator, namespaces=namespaces,
step=step, total=total, g_content=content,
@@ -1941,7 +1954,8 @@
self.getcategoryinfo(category)
if not hasattr(category, "_catinfo"):
# a category that exists but has no contents returns no API result
- category._catinfo = {'size': 0, 'pages': 0, 'files': 0, 'subcats': 0}
+ category._catinfo = {'size': 0, 'pages': 0, 'files': 0,
+ 'subcats': 0}
return category._catinfo
@deprecate_arg("throttle", None)
@@ -1985,7 +1999,8 @@
raise Error("allpages: only one namespace permitted.")
if includeredirects is not None:
pywikibot.debug(
- u"allpages: 'includeRedirects' argument is deprecated; use 'filterredirs'.",
+ u"allpages: 'includeRedirects' argument is deprecated; "
+ u"use 'filterredirs'.",
_logger)
if includeredirects:
if includeredirects == "only":
@@ -2186,11 +2201,13 @@
if reverse:
if starttime > endtime:
raise pywikibot.Error(
- "blocks: starttime must be before endtime with reverse=True")
+ "blocks: "
+ "starttime must be before endtime with reverse=True")
else:
if endtime > starttime:
raise pywikibot.Error(
- "blocks: endtime must be before starttime with reverse=False")
+ "blocks: "
+ "endtime must be before starttime with reverse=False")
bkgen = self._generator(api.ListGenerator, type_arg="blocks",
step=step, total=total)
bkgen.request["bkprop"] = "id|user|by|timestamp|expiry|reason|range|flags"
@@ -2263,11 +2280,13 @@
if reverse:
if end < start:
raise Error(
- "logevents: end must be later than start with reverse=True")
+ "logevents: "
+ "end must be later than start with reverse=True")
else:
if start < end:
raise Error(
- "logevents: start must be later than end with reverse=False")
+ "logevents: "
+ "start must be later than end with reverse=False")
legen = self._generator(api.LogEntryListGenerator, type_arg=logtype,
step=step, total=total)
if logtype is not None:
@@ -2331,11 +2350,13 @@
if reverse:
if end < start:
raise Error(
- "recentchanges: end must be later than start with reverse=True")
+ "recentchanges: "
+ "end must be later than start with reverse=True")
else:
if start < end:
raise Error(
- "recentchanges: start must be later than end with reverse=False")
+ "recentchanges: "
+ "start must be later than end with reverse=False")
rcgen = self._generator(api.ListGenerator, type_arg="recentchanges",
rcprop="user|comment|timestamp|title|ids"
"|sizes|redirect|loginfo|flags",
@@ -2363,7 +2384,8 @@
'anon': showAnon,
'redirect': showRedirects,
}
- if showPatrolled is not None and (self.has_right('patrol') or self.has_right('patrolmarks')):
+ if showPatrolled is not None and (
+ self.has_right('patrol') or self.has_right('patrolmarks')):
rcgen.request['rcprop'] += '|patrolled'
filters['patrolled'] = showPatrolled
rcshow = []
@@ -2394,7 +2416,8 @@
@param where: Where to search; value must be "text" or "titles" (many
wikis do not support title search)
@param namespaces: search only in these namespaces (defaults to 0)
- @type namespaces: list of ints, or an empty list to signal all namespaces
+ @type namespaces: list of ints, or an empty list to signal all
+ namespaces
@param getredirects: if True, include redirects in results
@param content: if True, load the current content of each iterated page
(default False)
@@ -2432,7 +2455,8 @@
@param reverse: Iterate oldest contributions first (default: newest)
@param showMinor: if True, iterate only minor edits; if False and
not None, iterate only non-minor edits (default: iterate both)
- @param top_only: if True, iterate only edits which are the latest revision
+ @param top_only: if True, iterate only edits which are the latest
+ revision
"""
if not (user or userprefix):
@@ -2442,11 +2466,13 @@
if reverse:
if end < start:
raise Error(
- "usercontribs: end must be later than start with reverse=True")
+ "usercontribs: "
+ "end must be later than start with reverse=True")
else:
if start < end:
raise Error(
- "usercontribs: start must be later than end with reverse=False")
+ "usercontribs: "
+ "start must be later than end with reverse=False")
ucgen = self._generator(api.ListGenerator, type_arg="usercontribs",
ucprop="ids|title|timestamp|comment|flags",
namespaces=namespaces, step=step,
@@ -2489,11 +2515,13 @@
if reverse:
if end < start:
raise Error(
- "watchlist_revs: end must be later than start with reverse=True")
+ "watchlist_revs: "
+ "end must be later than start with reverse=True")
else:
if start < end:
raise Error(
- "watchlist_revs: start must be later than end with reverse=False")
+ "watchlist_revs: "
+ "start must be later than end with reverse=False")
wlgen = self._generator(api.ListGenerator, type_arg="watchlist",
wlprop="user|comment|timestamp|title|ids|flags",
wlallrev="", namespaces=namespaces,
@@ -2538,11 +2566,13 @@
if reverse:
if end < start:
raise Error(
-"deletedrevs: end must be later than start with reverse=True")
+ "deletedrevs: "
+ "end must be later than start with reverse=True")
else:
if start < end:
raise Error(
- "deletedrevs: start must be later than end with reverse=False")
+ "deletedrevs: "
+ "start must be later than end with reverse=False")
if not self.logged_in():
self.login()
if "deletedhistory" not in self.userinfo['rights']:
@@ -2552,7 +2582,8 @@
pass
if "deletedhistory" not in self.userinfo['rights']:
raise Error(
- "deletedrevs: User:%s not authorized to access deleted revisions."
+ "deletedrevs: "
+ "User:%s not authorized to access deleted revisions."
% self.user())
if get_text:
if "undelete" not in self.userinfo['rights']:
@@ -2562,7 +2593,8 @@
pass
if "undelete" not in self.userinfo['rights']:
raise Error(
- "deletedrevs: User:%s not authorized to view deleted content."
+ "deletedrevs: "
+ "User:%s not authorized to view deleted content."
% self.user())
drgen = self._generator(api.ListGenerator, type_arg="deletedrevs",
@@ -2570,7 +2602,8 @@
drprop="revid|user|comment|minor",
step=step, total=total)
if get_text:
- drgen.request['drprop'] = drgen.request['drprop'] + "|content|token"
+ drgen.request['drprop'] = (drgen.request['drprop'] +
+ "|content|token")
if start is not None:
drgen.request["drstart"] = str(start)
if end is not None:
@@ -2729,8 +2762,10 @@
except api.APIError, err:
self.unlock_page(page)
if err.code.endswith("anon") and self.logged_in():
- pywikibot.debug(u"editpage: received '%s' even though bot is logged in" % err.code,
- _logger)
+ pywikibot.debug(
+ u"editpage: received '%s' even though bot is logged in"
+ % err.code,
+ _logger)
errdata = {
'site': self,
'title': page.title(withSection=False),
@@ -2738,8 +2773,9 @@
'info': err.info
}
if err.code == "spamdetected":
- raise SpamfilterError(self._ep_errors[err.code] % errdata
- + err.info[err.info.index("fragment: ") + 9:])
+ raise SpamfilterError(
+ self._ep_errors[err.code] % errdata
+ + err.info[err.info.index("fragment: ") + 9:])
if err.code == "editconflict":
raise EditConflict(self._ep_errors[err.code] % errdata)
@@ -2774,25 +2810,31 @@
continue
elif "url" in captcha:
import webbrowser
- webbrowser.open(self.family.protocol(self.code) + '://' + self.family.hostname(self.code) + captcha["url"])
+ webbrowser.open('%s://%s%s'
+ % (self.family.protocol(self.code),
+ self.family.hostname(self.code),
+ captcha["url"]))
req['captchaword'] = cap_answerwikipedia.input(
-"Please view CAPTCHA in your browser, then type answer here:")
+ "Please view CAPTCHA in your browser, "
+ "then type answer here:")
continue
else:
self.unlock_page(page)
pywikibot.error(
- u"editpage: unknown CAPTCHA response %s, page not saved"
+ u"editpage: unknown CAPTCHA response %s, "
+ u"page not saved"
% captcha)
return False
else:
self.unlock_page(page)
- pywikibot.error(u"editpage: unknown failure reason %s" % str(result))
+ pywikibot.error(u"editpage: unknown failure reason %s"
+ % str(result))
return False
else:
self.unlock_page(page)
pywikibot.error(
- u"editpage: Unknown result code '%s' received; page not saved"
- % result["edit"]["result"])
+ u"editpage: Unknown result code '%s' received; "
+ u"page not saved" % result["edit"]["result"])
pywikibot.log(str(result))
return False
@@ -2864,7 +2906,8 @@
except api.APIError, err:
if err.code.endswith("anon") and self.logged_in():
pywikibot.debug(
- u"movepage: received '%s' even though bot is logged in" % err.code,
+ u"movepage: received '%s' even though bot is logged in"
+ % err.code,
_logger)
errdata = {
'site': self,
@@ -2888,7 +2931,8 @@
#TODO: Check for talkmove-error messages
if "talkmove-error-code" in result["move"]:
pywikibot.warning(
- u"movepage: Talk page %s not moved" % (page.toggleTalkPage().title(asLink=True)))
+ u"movepage: Talk page %s not moved"
+ % (page.toggleTalkPage().title(asLink=True)))
return pywikibot.Page(page, newtitle)
# catalog of rollback errors for use in error messages
@@ -2911,7 +2955,8 @@
"""
if len(page._revisions) < 2:
raise pywikibot.Error(
- u"Rollback of %s aborted; load revision history first." % page.title(asLink=True))
+ u"Rollback of %s aborted; load revision history first."
+ % page.title(asLink=True))
last_rev = page._revisions[page.latestRevision()]
last_user = last_rev.user
for rev in sorted(page._revisions.keys(), reverse=True):
@@ -2921,7 +2966,8 @@
break
else:
raise pywikibot.Error(
- u"Rollback of %s aborted; only one user in revision history." % page.title(asLink=True))
+ u"Rollback of %s aborted; only one user in revision history."
+ % page.title(asLink=True))
summary = summary or (
u"Reverted edits by [[Special:Contributions/%(last_user)s|%(last_user)s]] "
u"([[User talk:%(last_user)s|Talk]]) to last version by %(prev_user)s"
@@ -2967,7 +3013,8 @@
try:
self.login(sysop=True)
except pywikibot.NoUsername, e:
- raise NoUsername("delete: Unable to login as sysop (%s)" % e.__class__.__name__)
+ raise NoUsername("delete: Unable to login as sysop (%s)"
+ % e.__class__.__name__)
if not self.logged_in(sysop=True):
raise NoUsername("delete: Unable to login as sysop")
token = self.token(page, "delete")
@@ -2985,7 +3032,8 @@
}
if err.code in self._dl_errors:
raise Error(self._dl_errors[err.code] % errdata)
- pywikibot.debug(u"delete: Unexpected error code '%s' received." % err.code,
+ pywikibot.debug(u"delete: Unexpected error code '%s' received."
+ % err.code,
_logger)
raise
finally:
@@ -2996,14 +3044,14 @@
#TODO: implement patrol
@must_be(group='sysop')
- def blockuser(self, user, expiry, reason, anononly=True, nocreate=True, autoblock=True,
- noemail=False, reblock=False):
+ def blockuser(self, user, expiry, reason, anononly=True, nocreate=True,
+ autoblock=True, noemail=False, reblock=False):
token = self.token(user, 'block')
if isinstance(expiry, pywikibot.Timestamp):
expiry = expiry.toISOformat()
- req = api.Request(site=self, action='block', user=user.username, expiry=expiry,
- reason=reason, token=token)
+ req = api.Request(site=self, action='block', user=user.username,
+ expiry=expiry, reason=reason, token=token)
if anononly:
req['anononly'] = ''
if nocreate:
@@ -3027,7 +3075,8 @@
"""
token = self.token(page, "watch")
- req = api.Request(action="watch", token=token, title=page.title(withSection=False))
+ req = api.Request(action="watch", token=token,
+ title=page.title(withSection=False))
if unwatch:
req["unwatch"] = ""
result = req.submit()
@@ -3064,8 +3113,8 @@
NOTE 2: it returns the image title WITHOUT the image namespace.
"""
- if hash_found is None: # If the hash is none return None and not continue
- return None
+ if hash_found is None:
+ return
return [image.title(withNamespace=False)
for image in self.allimages(sha1=hash_found)]
@@ -3108,20 +3157,18 @@
# check for required user right
if "upload" not in self.userinfo["rights"]:
raise pywikibot.Error(
- "User '%s' does not have upload rights on site %s." % (self.user(), self)
- )
+ "User '%s' does not have upload rights on site %s."
+ % (self.user(), self))
# check for required parameters
if (source_filename and source_url)\
or (source_filename is None and source_url is None):
- raise ValueError(
-"APISite.upload: must provide either source_filename or source_url, not both."
- )
+ raise ValueError("APISite.upload: must provide either "
+ "source_filename or source_url, not both.")
if comment is None:
comment = imagepage.text
if not comment:
- raise ValueError(
-"APISite.upload: cannot upload file without a summary/description."
- )
+ raise ValueError("APISite.upload: cannot upload file without "
+ "a summary/description.")
if text is None:
text = imagepage.text
if not text:
@@ -3301,7 +3348,9 @@
@deprecate_arg("number", None)
@deprecate_arg("repeat", None)
def unwatchedpages(self, step=None, total=None):
- """Yield Pages from Special:Unwatchedpages (requires Admin privileges)."""
+ """Yield Pages from Special:Unwatchedpages (requires Admin privileges).
+
+ """
uwgen = self._generator(api.PageGenerator,
type_arg="querypage", gqppage="Unwatchedpages",
step=step, total=total)
@@ -3345,7 +3394,8 @@
@deprecate_arg("number", None)
@deprecate_arg("repeat", None)
- def uncategorizedtemplates(self, number=None, repeat=True, step=None, total=None):
+ def uncategorizedtemplates(self, number=None, repeat=True, step=None,
+ total=None):
"""Yield Pages from Special:Uncategorizedtemplates."""
utgen = self._generator(api.PageGenerator,
type_arg="querypage",
@@ -3445,7 +3495,8 @@
def _get_propertyitem(self, props, source, **params):
"""generic method to get the data for multiple Wikibase items"""
wbdata = self.get_item(source, props=props, **params)
- assert props in wbdata, "API wbgetentities response lacks %s key" % props
+ assert props in wbdata, \
+ "API wbgetentities response lacks %s key" % props
return wbdata[props]
@deprecated("pywikibot.WikibasePage")
@@ -3457,10 +3508,13 @@
wbrequest = api.Request(site=self, action="wbgetentities", ids=ids,
**params)
wbdata = wbrequest.submit()
- assert 'success' in wbdata, "API wbgetentities response lacks 'success' key"
+ assert 'success' in wbdata, \
+ "API wbgetentities response lacks 'success' key"
assert wbdata['success'] == 1, "API 'success' key ist not 1"
- assert 'entities' in wbdata, "API wbgetentities response lacks 'entities' key"
- assert ids in wbdata['entities'], "API wbgetentities response lacks %s key" % ids
+ assert 'entities' in wbdata, \
+ "API wbgetentities response lacks 'entities' key"
+ assert ids in wbdata['entities'], \
+ "API wbgetentities response lacks %s key" % ids
return wbdata['entities'][ids]
else:
# not implemented yet
@@ -3509,7 +3563,7 @@
for qid in data['entities']:
item = pywikibot.ItemPage(self, qid)
item._content = data['entities'][qid]
- item.get() # This parses the json and preloads the various properties
+ item.get() # parses json and preloads the various properties
yield item
def getPropertyType(self, prop):
@@ -3553,7 +3607,8 @@
params['bot'] = 1
if 'baserevid' in kwargs and kwargs['baserevid']:
params['baserevid'] = kwargs['baserevid']
- params['token'] = self.token(pywikibot.Page(self, u'Main Page'), 'edit') # Use a dummy page
+ params['token'] = self.token(pywikibot.Page(self, u'Main Page'),
+ 'edit') # Use a dummy page
for arg in kwargs:
if arg in ['clear', 'data', 'exclude', 'summary']:
params[arg] = kwargs[arg]
@@ -3632,7 +3687,7 @@
params = dict(action='wbsetreference',
statement=claim.snak,
)
- if claim.on_item: # I can't think of when this would be false, but lets be safe
+ if claim.on_item: # I think this wouldn't be false, but lets be safe
params['baserevid'] = claim.on_item.lastrevid
if bot:
params['bot'] = 1
@@ -3654,7 +3709,8 @@
'value': sourceclaim._formatDataValue(),
}
else:
- raise NotImplementedError('%s datatype is not supported yet.' % sourceclaim.getType())
+ raise NotImplementedError('%s datatype is not supported yet.'
+ % sourceclaim.getType())
valuesnaks = []
if sourceclaim.getID() in snak:
valuesnaks = snak[sourceclaim.getID()]
@@ -3665,7 +3721,8 @@
)
snak[sourceclaim.getID()] = valuesnaks
- # set the hash if the source should be changed. if present, all claims of one source have the same hash
+ # set the hash if the source should be changed.
+ # if present, all claims of one source have the same hash
if not new and hasattr(sourceclaim, 'hash'):
params['reference'] = sourceclaim.hash
@@ -3693,7 +3750,7 @@
params = dict(action='wbsetqualifier',
claim=claim.snak,
)
- if claim.on_item: # I can't think of when this would be false, but lets be safe
+ if claim.on_item: # I think this wouldn't be false, but lets be safe
params['baserevid'] = claim.on_item.lastrevid
if bot:
params['bot'] = 1
@@ -3720,7 +3777,8 @@
if bot:
params['bot'] = 1
params['claim'] = '|'.join(claim.snak for claim in claims)
- params['token'] = self.token(pywikibot.Page(self, u'Main Page'), 'edit') # Use a dummy page
+ params['token'] = self.token(pywikibot.Page(self, u'Main Page'),
+ 'edit') # Use a dummy page
for kwarg in kwargs:
if kwarg in ['baserevid', 'summary']:
params[kwarg] = kwargs[kwarg]
@@ -3826,12 +3884,14 @@
self._cookies[index] = None
self._isLoggedIn[index] = False
else:
- tmp = '%s-%s-%s-login.data' % (self.family.name, self.code, username)
+ tmp = '%s-%s-%s-login.data' % (self.family.name, self.code,
+ username)
fn = config.datafilepath('login-data', tmp)
if not os.path.exists(fn):
self._cookies[index] = None
self._isLoggedIn[index] = False
else:
f = open(fn)
- self._cookies[index] = '; '.join([x.strip() for x in f.readlines()])
+ self._cookies[index] = '; '.join([x.strip()
+ for x in f.readlines()])
f.close()
--
To view, visit https://gerrit.wikimedia.org/r/91997
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ia3233f6647b394be16de888c548e84dadc1d1998
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change and it was merged.
Change subject: synchronize i18n.py with compat
......................................................................
synchronize i18n.py with compat
Change-Id: Ic04a243a2f120145b572f7d3013694ce32a44495
---
M pywikibot/i18n.py
1 file changed, 3 insertions(+), 2 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index 4a96bbe..d2d9cef 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -384,7 +384,7 @@
Support is implemented like in MediaWiki extension. If the tw message
contains a plural tag inside which looks like
{{PLURAL:<number>|<variant1>|<variant2>[|<variantn>]}}
- it takes that variant calculated by the plural_func depending on the number
+ it takes that variant calculated by the plural_rules depending on the number
value.
Examples:
@@ -502,6 +502,7 @@
default is os locale setting
"""
- code = config.userinterface_lang or locale.getdefaultlocale()[0].split('_')[0]
+ code = config.userinterface_lang or \
+ locale.getdefaultlocale()[0].split('_')[0]
trans = twtranslate(code, twtitle, parameters)
return pywikibot.input(trans, password)
--
To view, visit https://gerrit.wikimedia.org/r/91415
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ic04a243a2f120145b572f7d3013694ce32a44495
Gerrit-PatchSet: 2
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change and it was merged.
Change subject: remove obsolete sys import,
......................................................................
remove obsolete sys import,
pep8 changes synchronized with compat
Change-Id: I74984ae0194592262296409c62a0378619fb487c
---
M scripts/upload.py
1 file changed, 5 insertions(+), 5 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/scripts/upload.py b/scripts/upload.py
index f21e6e1..f3aefe4 100755
--- a/scripts/upload.py
+++ b/scripts/upload.py
@@ -28,7 +28,6 @@
#
import os
-import sys
import time
import urllib
import urlparse
@@ -43,9 +42,9 @@
verifyDescription=True, ignoreWarning=False,
targetSite=None, uploadByUrl=False):
"""
- ignoreWarning - Set this to True if you want to upload even if another
- file would be overwritten or another mistake would be
- risked.
+ @param ignoreWarning: Set this to True if you want to upload even if
+ another file would be overwritten or another mistake would be
+ risked.
"""
self.url = url
@@ -56,7 +55,8 @@
self.verifyDescription = verifyDescription
self.ignoreWarning = ignoreWarning
if config.upload_to_commons:
- self.targetSite = targetSite or pywikibot.Site('commons', 'commons')
+ self.targetSite = targetSite or pywikibot.Site('commons',
+ 'commons')
else:
self.targetSite = targetSite or pywikibot.Site()
self.targetSite.forceLogin()
--
To view, visit https://gerrit.wikimedia.org/r/91402
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I74984ae0194592262296409c62a0378619fb487c
Gerrit-PatchSet: 2
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Xqt has submitted this change and it was merged.
Change subject: pep8 changes
......................................................................
pep8 changes
Change-Id: Id82074241828db3a96e25659ea45e368de7edff8
---
M category.py
1 file changed, 155 insertions(+), 105 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/category.py b/category.py
index 2061a65..7dfa0e5 100644
--- a/category.py
+++ b/category.py
@@ -98,9 +98,14 @@
# Distributed under the terms of the MIT license.
#
-import os, re, pickle, bz2
+import os
+import re
+import pickle
+import bz2
import wikipedia as pywikibot
-import catlib, config, pagegenerators
+import catlib
+import config
+import pagegenerators
from pywikibot import i18n
# This is required for the text that is shown when you run this script
@@ -110,14 +115,15 @@
}
cfd_templates = {
- 'wikipedia' : {
- 'en':[u'cfd', u'cfr', u'cfru', u'cfr-speedy', u'cfm', u'cfdu'],
- 'fi':[u'roskaa', u'poistettava', u'korjattava/nimi', u'yhdistettäväLuokka'],
- 'he':[u'הצבעת מחיקה', u'למחוק'],
- 'nl':[u'categorieweg', u'catweg', u'wegcat', u'weg2']
+ 'wikipedia': {
+ 'en': [u'cfd', u'cfr', u'cfru', u'cfr-speedy', u'cfm', u'cfdu'],
+ 'fi': [u'roskaa', u'poistettava', u'korjattava/nimi',
+ u'yhdistettäväLuokka'],
+ 'he': [u'הצבעת מחיקה', u'למחוק'],
+ 'nl': [u'categorieweg', u'catweg', u'wegcat', u'weg2']
},
- 'commons' : {
- 'commons':[u'cfd', u'move']
+ 'commons': {
+ 'commons': [u'cfd', u'move']
}
}
@@ -128,7 +134,7 @@
over and over again
'''
- def __init__(self, rebuild = False, filename = 'category.dump.bz2'):
+ def __init__(self, rebuild=False, filename='category.dump.bz2'):
if rebuild:
self.rebuild()
else:
@@ -140,7 +146,8 @@
% pywikibot.config.shortpath(filename))
databases = pickle.load(f)
f.close()
- # keys are categories, values are 2-tuples with lists as entries.
+ # keys are categories, values are 2-tuples with lists as
+ # entries.
self.catContentDB = databases['catContentDB']
# like the above, but for supercategories
self.superclassDB = databases['superclassDB']
@@ -150,8 +157,8 @@
self.rebuild()
def rebuild(self):
- self.catContentDB={}
- self.superclassDB={}
+ self.catContentDB = {}
+ self.superclassDB = {}
def getSubcats(self, supercat):
'''For a given supercategory, return a list of Categorys for all its
@@ -171,8 +178,8 @@
def getArticles(self, cat):
'''For a given category, return a list of Pages for all its articles.
- Saves this list in a temporary database so that it won't be loaded from the
- server next time it's required.
+ Saves this list in a temporary database so that it won't be loaded from
+ the server next time it's required.
'''
# if we already know which articles exist here
@@ -195,7 +202,7 @@
self.superclassDB[subcat] = supercatlist
return supercatlist
- def dump(self, filename = 'category.dump.bz2'):
+ def dump(self, filename='category.dump.bz2'):
'''Saves the contents of the dictionaries superclassDB and catContentDB
to disk.
@@ -266,8 +273,7 @@
# pull last part of the name to the beginning, and append the
# rest after a comma; e.g., "John von Neumann" becomes
# "Neumann, John von"
- sorted_key = split_string[-1] + ', ' + \
- ' '.join(split_string[:-1])
+ sorted_key = split_string[-1] + ', ' + ' '.join(split_string[:-1])
# give explicit sort key
return pywikibot.Page(site, catlink.title() + '|' + sorted_key)
else:
@@ -277,8 +283,8 @@
self.newcatTitle = pywikibot.input(
u'Category to add (do not give namespace):')
if not self.site.nocapitalize:
- self.newcatTitle = self.newcatTitle[:1].upper() + \
- self.newcatTitle[1:]
+ self.newcatTitle = (self.newcatTitle[:1].upper() +
+ self.newcatTitle[1:])
if not self.editSummary:
self.editSummary = i18n.twtranslate(self.site, 'category-adding',
{'newcat': self.newcatTitle})
@@ -320,7 +326,7 @@
if text != page.get():
# show what was changed
pywikibot.showDiff(page.get(), text)
- pywikibot.output(u'Comment: %s' %comment)
+ pywikibot.output(u'Comment: %s' % comment)
if not self.dry:
if not self.always:
confirm = 'y'
@@ -335,7 +341,8 @@
if confirm == 'y':
self.always = True
break
- else: break
+ else:
+ break
if self.always or choice == 'y':
try:
# Save the page
@@ -350,8 +357,8 @@
% (page.title()))
except pywikibot.SpamfilterError, error:
pywikibot.output(
-u'Cannot change %s because of spam blacklist entry %s'
- % (page.title(), error.url))
+ u'Cannot change %s because of spam blacklist entry '
+ u'%s' % (page.title(), error.url))
else:
return True
return False
@@ -411,21 +418,21 @@
if self.useSummaryForDeletion and self.editSummary:
reason = self.editSummary
else:
- reason = i18n.twtranslate(site, 'category-was-moved') \
- % {'newcat': self.newCatTitle, 'title': self.newCatTitle}
-
+ reason = i18n.twtranslate(site, 'category-was-moved',
+ {'newcat': self.newCatTitle,
+ 'title': self.newCatTitle})
+
if not self.editSummary:
- self.editSummary = i18n.twtranslate(site, 'category-changing') \
- % {'oldcat':self.oldCat.title(),
- 'newcat':newCat.title()}
+ self.editSummary = i18n.twtranslate(site, 'category-changing',
+ {'oldcat': self.oldCat.title(),
+ 'newcat': newCat.title()})
# Copy the category contents to the new category page
copied = False
oldMovedTalk = None
if self.oldCat.exists() and self.moveCatPage:
copied = self.oldCat.copyAndKeep(
- self.newCatTitle,
- pywikibot.translate(site, cfd_templates))
+ self.newCatTitle, pywikibot.translate(site, cfd_templates))
# Also move the talk page
if copied:
oldTalk = self.oldCat.toggleTalkPage()
@@ -448,9 +455,9 @@
history = self.oldCat.getVersionHistoryTable()
# Set the section title for the old cat's history on the new
# cat's talk page.
- sectionTitle = i18n.twtranslate(site,
- 'category-section-title') \
- % {'oldcat': self.oldCat.title()}
+ sectionTitle = i18n.twtranslate(
+ site, 'category-section-title',
+ {'oldcat': self.oldCat.title()})
#Should be OK, we are within if self.oldCat.exists()
historySection = u'\n== %s ==\n%s' % (sectionTitle, history)
try:
@@ -464,7 +471,8 @@
% {'oldcat': self.oldCat.title()})
except:
pywikibot.output(
- 'History of the category has not been saved to new talk page')
+ 'History of the category has not been saved to new '
+ 'talk page')
#TODO: some nicer exception handling (not too important)
# first move the page, than tagg the vh
@@ -491,12 +499,12 @@
inPlace=self.inPlace)
# Delete the old category and its moved talk page
- if copied and self.deleteEmptySourceCat == True:
+ if copied and self.deleteEmptySourceCat:
if self.oldCat.isEmptyCategory():
confirm = not self.batchMode
- self.oldCat.delete(reason, confirm, mark = True)
+ self.oldCat.delete(reason, confirm, mark=True)
if oldMovedTalk is not None:
- oldMovedTalk.delete(reason, confirm, mark = True)
+ oldMovedTalk.delete(reason, confirm, mark=True)
else:
pywikibot.output('Couldn\'t delete %s - not empty.'
% self.oldCat.title())
@@ -504,7 +512,9 @@
class CategoryListifyRobot:
'''Creates a list containing all of the members in a category.'''
- def __init__(self, catTitle, listTitle, editSummary, overwrite = False, showImages = False, subCats = False, talkPages = False, recurse = False):
+ def __init__(self, catTitle, listTitle, editSummary, overwrite=False,
+ showImages=False, subCats=False, talkPages=False,
+ recurse=False):
self.editSummary = editSummary
self.overwrite = overwrite
self.showImages = showImages
@@ -516,7 +526,7 @@
self.recurse = recurse
def run(self):
- listOfArticles = self.cat.articlesList(recurse = self.recurse)
+ listOfArticles = self.cat.articlesList(recurse=self.recurse)
if self.subCats:
listOfArticles += self.cat.subcategoriesList()
if not self.editSummary:
@@ -527,18 +537,24 @@
listString = ""
for article in listOfArticles:
- if (not article.isImage() or self.showImages) and not article.isCategory():
+ if (not article.isImage() or
+ self.showImages) and not article.isCategory():
if self.talkPages and not article.isTalkPage():
- listString = listString + "*[[%s]] -- [[%s|talk]]\n" % (article.title(), article.toggleTalkPage().title())
+ listString += "*[[%s]] -- [[%s|talk]]\n" \
+ % (article.title(),
+ article.toggleTalkPage().title())
else:
- listString = listString + "*[[%s]]\n" % article.title()
+ listString += "*[[%s]]\n" % article.title()
else:
if self.talkPages and not article.isTalkPage():
- listString = listString + "*[[:%s]] -- [[%s|talk]]\n" % (article.title(), article.toggleTalkPage().title())
+ listString += "*[[:%s]] -- [[%s|talk]]\n" \
+ % (article.title(),
+ article.toggleTalkPage().title())
else:
- listString = listString + "*[[:%s]]\n" % article.title()
+ listString += "*[[:%s]]\n" % article.title()
if self.list.exists() and not self.overwrite:
- pywikibot.output(u'Page %s already exists, aborting.' % self.list.title())
+ pywikibot.output(u'Page %s already exists, aborting.'
+ % self.list.title())
else:
self.list.put(listString, comment=self.editSummary)
@@ -557,7 +573,7 @@
pagesonly=False):
self.editSummary = editSummary
self.site = pywikibot.getSite()
- self.cat = catlib.Category(self.site, 'Category:'+ catTitle)
+ self.cat = catlib.Category(self.site, 'Category:' + catTitle)
# get edit summary message
self.useSummaryForDeletion = useSummaryForDeletion
self.batchMode = batchMode
@@ -569,23 +585,30 @@
{'oldcat': self.cat.title()})
def run(self):
- articles = self.cat.articlesList(recurse = 0)
+ articles = self.cat.articlesList(recurse=0)
if len(articles) == 0:
- pywikibot.output(u'There are no articles in category %s' % self.cat.title())
+ pywikibot.output(u'There are no articles in category %s'
+ % self.cat.title())
else:
for article in articles:
- if not self.titleRegex or re.search(self.titleRegex,article.title()):
- catlib.change_category(article, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
+ if not self.titleRegex or re.search(self.titleRegex,
+ article.title()):
+ catlib.change_category(article, self.cat, None,
+ comment=self.editSummary,
+ inPlace=self.inPlace)
if self.pagesonly:
return
# Also removes the category tag from subcategories' pages
- subcategories = self.cat.subcategoriesList(recurse = 0)
+ subcategories = self.cat.subcategoriesList(recurse=0)
if len(subcategories) == 0:
- pywikibot.output(u'There are no subcategories in category %s' % self.cat.title())
+ pywikibot.output(u'There are no subcategories in category %s'
+ % self.cat.title())
else:
for subcategory in subcategories:
- catlib.change_category(subcategory, self.cat, None, comment = self.editSummary, inPlace = self.inPlace)
+ catlib.change_category(subcategory, self.cat, None,
+ comment=self.editSummary,
+ inPlace=self.inPlace)
# Deletes the category page
if self.cat.exists() and self.cat.isEmptyCategory():
if self.useSummaryForDeletion and self.editSummary:
@@ -596,7 +619,9 @@
try:
self.cat.delete(reason, not self.batchMode)
except pywikibot.NoUsername:
- pywikibot.output(u'You\'re not setup sysop info, category will not delete.' % self.cat.site())
+ pywikibot.output(
+ u'You\'re not setup sysop info, category will not delete.'
+ % self.cat.site())
return
if (talkPage.exists()):
talkPage.delete(reason=reason, prompt=not self.batchMode)
@@ -612,8 +637,8 @@
in the category. It will ask you to type the number of the appropriate
replacement, and perform the change robotically.
- If you don't want to move the article to a subcategory or supercategory, but to
- another category, you can use the 'j' (jump) command.
+ If you don't want to move the article to a subcategory or supercategory, but
+ to another category, you can use the 'j' (jump) command.
Typing 's' will leave the complete page unchanged.
@@ -630,8 +655,9 @@
self.catTitle = catTitle
self.catDB = catDB
self.site = pywikibot.getSite()
- self.editSummary = i18n.twtranslate(self.site, 'category-changing')\
- % {'oldcat':self.catTitle, 'newcat':u''}
+ self.editSummary = i18n.twtranslate(self.site, 'category-changing',
+ {'oldcat': self.catTitle,
+ 'newcat': u''})
def move_to_category(self, article, original_cat, current_cat):
'''
@@ -644,21 +670,24 @@
pywikibot.output(u'')
# Show the title of the page where the link was found.
# Highlight the title in purple.
- pywikibot.output(u'Treating page \03{lightpurple}%s\03{default}, currently in \03{lightpurple}%s\03{default}' % (article.title(), current_cat.title()))
+ pywikibot.output(
+ u'Treating page \03{lightpurple}%s\03{default}, '
+ u'currently in \03{lightpurple}%s\03{default}'
+ % (article.title(), current_cat.title()))
# Determine a reasonable amount of context to print
try:
- full_text = article.get(get_redirect = True)
+ full_text = article.get(get_redirect=True)
except pywikibot.NoPage:
pywikibot.output(u'Page %s not found.' % article.title())
return
try:
contextLength = full_text.index('\n\n')
- except ValueError: # substring not found
+ except ValueError: # substring not found
contextLength = 500
- if full_text.startswith(u'[['): # probably an image
+ if full_text.startswith(u'[['): # probably an image
# Add extra paragraph.
- contextLength = full_text.find('\n\n', contextLength+2)
+ contextLength = full_text.find('\n\n', contextLength + 2)
if contextLength > 1000 or contextLength < 0:
contextLength = 500
print
@@ -675,10 +704,12 @@
# show subcategories as possible choices (with numbers)
for i in range(len(supercatlist)):
# layout: we don't expect a cat to have more than 10 supercats
- alternatives += (u"u%d - Move up to %s\n" % (i, supercatlist[i].title()))
+ alternatives += (u"u%d - Move up to %s\n"
+ % (i, supercatlist[i].title()))
for i in range(len(subcatlist)):
# layout: we don't expect a cat to have more than 100 subcats
- alternatives += (u"%2d - Move down to %s\n" % (i, subcatlist[i].title()))
+ alternatives += (u"%2d - Move down to %s\n"
+ % (i, subcatlist[i].title()))
alternatives += u" j - Jump to another category\n"
alternatives += u" s - Skip this article\n"
alternatives += u" r - Remove this category tag\n"
@@ -693,7 +724,9 @@
pywikibot.output(alternatives)
choice = pywikibot.input(u"Option:")
else:
- choice = pywikibot.input(u"Option (#, [j]ump, [s]kip, [r]emove, [l]ist, [m]ore context, [RETURN]):")
+ choice = pywikibot.input(
+ u"Option (#, [j]ump, [s]kip, [r]emove, [l]ist, "
+ u"[m]ore context, [RETURN]):")
if choice in ['s', 'S']:
flag = True
elif choice == '':
@@ -702,30 +735,42 @@
print 'No changes necessary.'
else:
newcat = u'[[:%s|%s]]' % (current_cat.title(savetitle=True),
- current_cat.title(withNamespace=False))
- editsum = i18n.twtranslate(pywikibot.getSite(),
- 'category-replacing',
- {'oldcat': original_cat.title(withNamespace=False),
- 'newcat': newcat})
+ current_cat.title(
+ withNamespace=False))
+ editsum = i18n.twtranslate(
+ pywikibot.getSite(), 'category-replacing',
+ {'oldcat': original_cat.title(withNamespace=False),
+ 'newcat': newcat})
if pywikibot.getSite().family.name == "commons":
- if original_cat.title(withNamespace=False).startswith("Media needing categories as of"):
+ if original_cat.title(withNamespace=False).startswith(
+ "Media needing categories as of"):
parts = original_cat.title().split()
- catstring = u"{{Uncategorized|year=%s|month=%s|day=%s}}"%(parts[-1], parts[-2], parts[-3])
+ catstring = u"{{Uncategorized|year=%s|month=%s|day=%s}}" \
+ % (parts[-1], parts[-2], parts[-3])
if catstring in article.get():
- article.put(article.get().replace(catstring, u"[[%s]]"%current_cat.title(savetitle=True)), comment = editsum)
+ article.put(
+ article.get().replace(catstring,
+ u"[[%s]]"
+ % current_cat.title(
+ savetitle=True)),
+ comment=editsum)
flag = True
if not flag:
- catlib.change_category(article, original_cat, current_cat, comment = editsum)
+ catlib.change_category(article, original_cat,
+ current_cat, comment=editsum)
flag = True
elif choice in ['j', 'J']:
- newCatTitle = pywikibot.input(u'Please enter the category the article should be moved to:')
- newCat = catlib.Category(pywikibot.getSite(), 'Category:' + newCatTitle)
+ newCatTitle = pywikibot.input(u'Please enter the category the '
+ u'article should be moved to:')
+ newCat = catlib.Category(pywikibot.getSite(),
+ 'Category:' + newCatTitle)
# recurse into chosen category
self.move_to_category(article, original_cat, newCat)
flag = True
elif choice in ['r', 'R']:
# remove the category tag
- catlib.change_category(article, original_cat, None, comment = self.editSummary)
+ catlib.change_category(article, original_cat, None,
+ comment=self.editSummary)
flag = True
elif choice in ['l', 'L']:
longchoice = True
@@ -744,15 +789,16 @@
pywikibot.output(u'* %s' % cat.title())
elif choice[0] == 'u':
try:
- choice=int(choice[1:])
+ choice = int(choice[1:])
except ValueError:
# user pressed an unknown command. Prompt him again.
continue
- self.move_to_category(article, original_cat, supercatlist[choice])
+ self.move_to_category(article, original_cat,
+ supercatlist[choice])
flag = True
else:
try:
- choice=int(choice)
+ choice = int(choice)
except ValueError:
# user pressed an unknown command. Prompt him again.
continue
@@ -763,7 +809,7 @@
def run(self):
cat = catlib.Category(self.site, 'Category:' + self.catTitle)
- articles = cat.articlesList(recurse = False)
+ articles = cat.articlesList(recurse=False)
if len(articles) == 0:
pywikibot.output(u'There are no articles in category ' + catTitle)
else:
@@ -788,7 +834,7 @@
the tree to stdout.
'''
- def __init__(self, catTitle, catDB, filename = None, maxDepth = 10):
+ def __init__(self, catTitle, catDB, filename=None, maxDepth=10):
self.catTitle = catTitle
self.catDB = catDB
if filename and not os.path.isabs(filename):
@@ -798,10 +844,10 @@
self.maxDepth = maxDepth
self.site = pywikibot.getSite()
- def treeview(self, cat, currentDepth = 0, parent = None):
+ def treeview(self, cat, currentDepth=0, parent=None):
'''
- Returns a multi-line string which contains a tree view of all subcategories
- of cat, up to level maxDepth. Recursively calls itself.
+ Returns a multi-line string which contains a tree view of all
+ subcategories of cat, up to level maxDepth. Recursively calls itself.
Parameters:
* cat - the Category of the node we're currently opening
@@ -812,8 +858,8 @@
result = u'#' * currentDepth
result += '[[:%s|%s]]' % (cat.title(), cat.title().split(':', 1)[1])
result += ' (%d)' % len(self.catDB.getArticles(cat))
- # We will remove an element of this array, but will need the original array
- # later, so we create a shallow copy with [:]
+ # We will remove an element of this array, but will need the original
+ # array later, so we create a shallow copy with [:]
supercats = self.catDB.getSupercats(cat)[:]
# Find out which other cats are supercats of the current cat
try:
@@ -824,15 +870,19 @@
supercat_names = []
for i in range(len(supercats)):
# create a list of wiki links to the supercategories
- supercat_names.append('[[:%s|%s]]' % (supercats[i].title(), supercats[i].title().split(':', 1)[1]))
- # print this list, separated with commas, using translations given in also_in_cats
+ supercat_names.append('[[:%s|%s]]'
+ % (supercats[i].title(),
+ supercats[i].title().split(':', 1)[1]))
+ # print this list, separated with commas, using translations
+ # given in also_in_cats
result += ' ' + i18n.twtranslate(self.site, 'category-also-in',
- {'alsocat': ', '.join(supercat_names)})
+ {'alsocat': ', '.join(
+ supercat_names)})
result += '\n'
if currentDepth < self.maxDepth:
for subcat in self.catDB.getSubcats(cat):
# recurse into subdirectories
- result += self.treeview(subcat, currentDepth + 1, parent = cat)
+ result += self.treeview(subcat, currentDepth + 1, parent=cat)
else:
if self.catDB.getSubcats(cat) != []:
# show that there are more categories beyond the depth limit
@@ -857,7 +907,7 @@
f.write(tree)
f.close()
else:
- pywikibot.output(tree, toStdout = True)
+ pywikibot.output(tree, toStdout=True)
def main(*args):
@@ -906,7 +956,7 @@
action = 'tree'
elif arg == 'listify':
action = 'listify'
- elif arg =='-nodelete':
+ elif arg == '-nodelete':
deleteEmptySourceCat = False
elif arg == '-person':
sort_by_last_name = True
@@ -968,18 +1018,18 @@
bot = AddCategory(gen, sort_by_last_name, create_pages, editSummary, follow_redirects)
bot.run()
elif action == 'remove':
- if (fromGiven == False):
- oldCatTitle = pywikibot.input(
-u'Please enter the name of the category that should be removed:')
+ if not fromGiven:
+ oldCatTitle = pywikibot.input(u'Please enter the name of the '
+ u'category that should be removed:')
bot = CategoryRemoveRobot(oldCatTitle, batchMode, editSummary,
useSummaryForDeletion, inPlace=inPlace,
pagesonly=pagesonly)
bot.run()
elif action == 'move':
- if (fromGiven == False):
+ if not fromGiven:
oldCatTitle = pywikibot.input(
u'Please enter the old name of the category:')
- if (toGiven == False):
+ if not toGiven:
newCatTitle = pywikibot.input(
u'Please enter the new name of the category:')
bot = CategoryMoveRobot(oldCatTitle, newCatTitle, batchMode,
@@ -995,15 +1045,15 @@
catTitle = pywikibot.input(
u'For which category do you want to create a tree view?')
filename = pywikibot.input(
- u'Please enter the name of the file where the tree should be saved,\n'
- u'or press enter to simply show the tree:')
+ u'Please enter the name of the file where the tree should be saved,'
+ u'\nor press enter to simply show the tree:')
bot = CategoryTreeRobot(catTitle, catDB, filename)
bot.run()
elif action == 'listify':
- if (fromGiven == False):
+ if not fromGiven:
oldCatTitle = pywikibot.input(
u'Please enter the name of the category to listify:')
- if (toGiven == False):
+ if not toGiven:
newCatTitle = pywikibot.input(
u'Please enter the name of the list to create:')
bot = CategoryListifyRobot(oldCatTitle, newCatTitle, editSummary,
--
To view, visit https://gerrit.wikimedia.org/r/92015
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Id82074241828db3a96e25659ea45e368de7edff8
Gerrit-PatchSet: 3
Gerrit-Project: pywikibot/compat
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Xqt has submitted this change and it was merged.
Change subject: Bugfix for python 2.5: "plural_rules" is the valid function
......................................................................
Bugfix for python 2.5: "plural_rules" is the valid function
Change-Id: Iaafa4ba2a8500eefad5277114c399470ee47358f
---
M pywikibot/i18n.py
1 file changed, 3 insertions(+), 3 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index d180604..9fb7ec1 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -25,7 +25,7 @@
@param code The language code
@type code string
@return a list of strings as language codes
-
+
If no translation is available to a specified language, translate() will
try each of the specified fallback languages, in order, until it finds
one with a translation, with 'en' and '_default' as a last resort.
@@ -387,7 +387,7 @@
Support is implemented like in MediaWiki extension. If the tw message
contains a plural tag inside which looks like
{{PLURAL:<number>|<variant1>|<variant2>[|<variantn>]}}
- it takes that variant calculated by the plural_func depending on the number
+ it takes that variant calculated by the plural_rules depending on the number
value.
Examples:
@@ -455,7 +455,7 @@
# Compatibility check for old python releases which are unable
# to use plural.py - use _default rules for all
if sys.version_info < (2, 5):
- plural_func = lambda n: (n != 1)
+ plural_rules = lambda n: (n != 1)
index = plural_rules(num)
else:
from plural import plural_rules
--
To view, visit https://gerrit.wikimedia.org/r/91414
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Iaafa4ba2a8500eefad5277114c399470ee47358f
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/compat
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Xqt has submitted this change and it was merged.
Change subject: remove obsolete sys import,
......................................................................
remove obsolete sys import,
pep8 changes synchronized with core
Change-Id: I7308bf431d2b205b74fad2623aa171b8f25424f8
---
M upload.py
1 file changed, 13 insertions(+), 8 deletions(-)
Approvals:
Xqt: Looks good to me, approved
diff --git a/upload.py b/upload.py
index 60bf087..11e76a5 100644
--- a/upload.py
+++ b/upload.py
@@ -19,18 +19,20 @@
"""
#
# (C) Rob W.W. Hooft, Andre Engels 2003-2004
-# (C) Pywikipedia bot team, 2003-2011
+# (C) Pywikipedia bot team, 2003-2013
#
# Distributed under the terms of the MIT license.
#
__version__='$Id$'
#
-import os, sys, time
+import os
+import time
import urllib
import mimetypes
import wikipedia as pywikibot
-import config, query
+import config
+import query
def post_multipart(site, address, fields, files, cookies):
""" Post fields and files to an http host as multipart/form-data.
@@ -82,8 +84,9 @@
class UploadRobot:
def __init__(self, url, urlEncoding=None, description=u'',
- useFilename=None, keepFilename=False, verifyDescription=True,
- ignoreWarning=False, targetSite=None, uploadByUrl=False):
+ useFilename=None, keepFilename=False,
+ verifyDescription=True, ignoreWarning=False,
+ targetSite=None, uploadByUrl=False):
"""
@param ignoreWarning: Set this to True if you want to upload even if
another file would be overwritten or another mistake would be
@@ -199,7 +202,7 @@
% filename)
ok = False
# FIXME: these 2 belong somewhere else, presumably in family
- forbidden = '/' # to be extended
+ forbidden = '/' # to be extended
allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi',
u'ogg', u'png', u'svg', u'xcf', u'djvu',
u'ogv', u'oga', u'tif', u'tiff')
@@ -207,7 +210,7 @@
while not ok:
ok = True
newfn = pywikibot.input(
- u'Enter a better name, or press enter to accept:')
+ u'Enter a better name, or press enter to accept:')
if newfn == "":
newfn = filename
ext = os.path.splitext(newfn)[1].lower().strip('.')
@@ -260,6 +263,8 @@
filename = self.process_filename()
+ site = self.targetSite
+
params = {
'action': 'upload',
'token': self.targetSite.getToken(),
@@ -277,7 +282,7 @@
if self.ignoreWarning:
params['ignorewarnings'] = 1
- pywikibot.output(u'Uploading file to %s via API....' % self.targetSite)
+ pywikibot.output(u'Uploading file to %s via API....' % site)
data = query.GetData(params, self.targetSite)
--
To view, visit https://gerrit.wikimedia.org/r/91403
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I7308bf431d2b205b74fad2623aa171b8f25424f8
Gerrit-PatchSet: 3
Gerrit-Project: pywikibot/compat
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot