jenkins-bot has submitted this change and it was merged.
Change subject: Remove implicit use of `pywikibot`
......................................................................
Remove implicit use of `pywikibot`
`pywikibot` was being used without an 'import pywikibot' and
this wasnt a syntax error as 'import pywikibot.tools' or similar
implicitly imports `pywikibot`.
However this import may not always occur if the sub-module has
already been loaded, such as if the package import fails but
some sub-modules have been imported.
Also remove the 'import pywikibot.tools' from pywikibot.page.
Bug: T113161
Change-Id: Id01888d3b9d847927d4adce236153ac4b91a0c72
---
M pywikibot/__init__.py
M pywikibot/comms/http.py
M pywikibot/page.py
3 files changed, 66 insertions(+), 43 deletions(-)
Approvals:
XZise: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index b75fa13..ba3aae3 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -26,19 +26,24 @@
from warnings import warn
-# Use pywikibot. prefix for all in-package imports; this is to prevent
-# confusion with similarly-named modules in version 1 framework, for users
-# who want to continue using both
+# logging must be imported first so that other modules can
+# use these logging methods during the initialisation sequence.
+from pywikibot.logging import (
+ critical, debug, error, exception, log, output, stdout, warning
+)
from pywikibot import config2 as config
from pywikibot.bot import (
- output, warning, error, critical, debug, stdout, exception,
- input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui, log,
+ input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui,
calledModuleName, Bot, CurrentPageBot, WikidataBot,
# the following are flagged as deprecated on usage
handleArgs,
)
+from pywikibot.bot_choice import (
+ QuitKeyboardInterrupt as _QuitKeyboardInterrupt,
+)
from pywikibot.data.api import UploadWarning as _UploadWarning
+from pywikibot.diff import PatchManager
from pywikibot.exceptions import (
Error, InvalidTitle, BadTitle, NoPage, NoMoveTarget, SectionError,
SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily,
@@ -51,14 +56,25 @@
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect, InterwikiRedirectPage,
WikiBaseError, CoordinateGlobeUnknownException,
+ DeprecatedPageNotFoundError as _DeprecatedPageNotFoundError,
+ _EmailUserError,
)
-from pywikibot.tools import PY2, UnicodeMixin, redirect_func
-from pywikibot.tools.formatter import color_format
+from pywikibot.family import Family
from pywikibot.i18n import translate
-from pywikibot.diff import PatchManager
+from pywikibot.site import BaseSite
+from pywikibot.tools import (
+ # __ to avoid conflict with ModuleDeprecationWrapper._deprecated
+ deprecated as __deprecated,
+ deprecate_arg as __deprecate_arg,
+ normalize_username,
+ redirect_func,
+ ModuleDeprecationWrapper as _ModuleDeprecationWrapper,
+ PY2,
+ UnicodeMixin,
+)
+from pywikibot.tools.formatter import color_format
import pywikibot.textlib as textlib
-import pywikibot.tools
textlib_methods = (
'unescape', 'replaceExcept', 'removeDisabledParts',
'removeHTMLParts',
@@ -108,8 +124,8 @@
globals()[_name] = wrapped_func
-deprecated = redirect_func(pywikibot.tools.deprecated)
-deprecate_arg = redirect_func(pywikibot.tools.deprecate_arg)
+deprecated = redirect_func(__deprecated)
+deprecate_arg = redirect_func(__deprecate_arg)
class Timestamp(datetime.datetime):
@@ -564,14 +580,14 @@
# Iterate through all families and look, which does apply to
# the given URL
for fam in config.family_files:
- family = pywikibot.family.Family.load(fam)
+ family = Family.load(fam)
code = family.from_url(url)
if code is not None:
matched_sites += [(code, family)]
if matched_sites:
if len(matched_sites) > 1:
- pywikibot.warning(
+ warning(
'Found multiple matches for URL "{0}": {1} (use
first)'
.format(url, ', '.join(str(s) for s in matched_sites)))
_url_cache[url] = matched_sites[0]
@@ -591,8 +607,8 @@
code = code or config.mylang
fam = fam or config.family
- if not isinstance(fam, pywikibot.family.Family):
- fam = pywikibot.family.Family.load(fam)
+ if not isinstance(fam, Family):
+ fam = Family.load(fam)
interface = interface or fam.interface(code)
@@ -612,10 +628,10 @@
except ImportError:
raise ValueError("Invalid interface name '%(interface)s'" %
locals())
- if not issubclass(interface, pywikibot.site.BaseSite):
+ if not issubclass(interface, BaseSite):
warning('Site called with interface=%s' % interface.__name__)
- user = pywikibot.tools.normalize_username(user)
+ user = normalize_username(user)
key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user)
if key not in _sites or not isinstance(_sites[key], interface):
_sites[key] = interface(code=code, fam=fam, user=user, sysop=sysop)
@@ -630,9 +646,10 @@
# alias for backwards-compability
-getSite = pywikibot.tools.redirect_func(Site, old_name='getSite')
+getSite = redirect_func(Site, old_name='getSite')
+# These imports depend on Wb* classes above.
from pywikibot.page import (
Page,
FilePage,
@@ -649,7 +666,7 @@
link_regex = re.compile(r'\[\[(?P<title>[^\]|[<>{}]*)(\|.*?)?\]\]')
-(a)pywikibot.tools.deprecated("comment parameter for page saving method")
+@__deprecated('comment parameter for page saving method')
def setAction(s):
"""Set a summary to use for changed page
submissions."""
config.default_edit_summary = s
@@ -752,20 +769,20 @@
_putthread.setName('Put-Thread')
_putthread.setDaemon(True)
-wrapper = pywikibot.tools.ModuleDeprecationWrapper(__name__)
+wrapper = _ModuleDeprecationWrapper(__name__)
wrapper._add_deprecated_attr('ImagePage', FilePage)
wrapper._add_deprecated_attr(
'cookie_jar', replacement_name='pywikibot.comms.http.cookie_jar')
wrapper._add_deprecated_attr(
- 'PageNotFound', pywikibot.exceptions.DeprecatedPageNotFoundError,
+ 'PageNotFound', _DeprecatedPageNotFoundError,
warning_message=('{0}.{1} is deprecated, and no longer '
'used by pywikibot; use http.fetch() instead.'))
wrapper._add_deprecated_attr(
- 'UserActionRefuse', pywikibot.exceptions._EmailUserError,
+ 'UserActionRefuse', _EmailUserError,
warning_message='UserActionRefuse is deprecated; '
'use UserRightsError and/or NotEmailableError instead.')
wrapper._add_deprecated_attr(
- 'QuitKeyboardInterrupt', pywikibot.bot.QuitKeyboardInterrupt,
+ 'QuitKeyboardInterrupt', _QuitKeyboardInterrupt,
warning_message='pywikibot.QuitKeyboardInterrupt is deprecated; '
'use pywikibot.bot.QuitKeyboardInterrupt instead.')
wrapper._add_deprecated_attr(
diff --git a/pywikibot/comms/http.py b/pywikibot/comms/http.py
index 7a54e07..8db7213 100644
--- a/pywikibot/comms/http.py
+++ b/pywikibot/comms/http.py
@@ -44,11 +44,16 @@
from urllib2 import quote
from pywikibot import config
+
+from pywikibot import __release__
+from pywikibot.bot import calledModuleName
+from pywikibot.comms import threadedhttp
from pywikibot.exceptions import (
FatalServerError, Server504Error, Server414Error
)
-from pywikibot.comms import threadedhttp
+from pywikibot.logging import critical, debug, error, log, warning
from pywikibot.tools import deprecate_arg, issue_deprecation_warning, PY2
+
import pywikibot.version
# The error message for failed SSL certificate verification
@@ -57,21 +62,21 @@
_logger = "comm.http"
-if (isinstance(pywikibot.config2.socket_timeout, tuple) and
+if (isinstance(config.socket_timeout, tuple) and
StrictVersion(requests.__version__) < StrictVersion('2.4.0')):
- pywikibot.warning('The configured timeout is a tuple but requests does not '
- 'support a tuple as a timeout. It uses the lower of the '
- 'two.')
- pywikibot.config2.socket_timeout = min(pywikibot.config2.socket_timeout)
+ warning('The configured timeout is a tuple but requests does not '
+ 'support a tuple as a timeout. It uses the lower of the '
+ 'two.')
+ config.socket_timeout = min(config.socket_timeout)
cookie_jar = cookielib.LWPCookieJar(
config.datafilepath('pywikibot.lwp'))
try:
cookie_jar.load()
except (IOError, cookielib.LoadError):
- pywikibot.debug(u"Loading cookies failed.", _logger)
+ debug('Loading cookies failed.', _logger)
else:
- pywikibot.debug(u"Loaded cookies from file.", _logger)
+ debug('Loaded cookies from file.', _logger)
session = requests.Session()
session.cookies = cookie_jar
@@ -84,17 +89,17 @@
if hasattr(sys, 'last_type'):
# we quit because of an exception
print(sys.last_type)
- pywikibot.critical(message)
+ critical(message)
else:
- pywikibot.log(message)
+ log(message)
- pywikibot.log('Network session closed.')
+ log('Network session closed.')
atexit.register(_flush)
USER_AGENT_PRODUCTS = {
'python': 'Python/' + '.'.join([str(i) for i in
sys.version_info]),
'http_backend': 'requests/' + requests.__version__,
- 'pwb': 'Pywikibot/' + pywikibot.__release__,
+ 'pwb': 'Pywikibot/' + __release__,
}
@@ -157,10 +162,12 @@
"""
values = USER_AGENT_PRODUCTS.copy()
- values['script'] = pywikibot.calledModuleName()
+ script_name = calledModuleName()
+
+ values['script'] = script_name
# TODO: script_product should add the script version, if known
- values['script_product'] = pywikibot.calledModuleName()
+ values['script_product'] = script_name
script_comments = []
username = ''
@@ -275,8 +282,8 @@
if auth is not None and len(auth) == 4:
if isinstance(requests_oauthlib, ImportError):
warn('%s' % requests_oauthlib, ImportWarning)
- pywikibot.error('OAuth authentication not supported: %s'
- % requests_oauthlib)
+ error('OAuth authentication not supported: %s'
+ % requests_oauthlib)
auth = None
else:
auth = requests_oauthlib.OAuth1(*auth)
@@ -321,8 +328,7 @@
# HTTP status 207 is also a success status for Webdav FINDPROP,
# used by the version module.
if request.status not in (200, 207):
- pywikibot.warning(u"Http response status %(status)s"
- % {'status': request.data.status_code})
+ warning('Http response status {0}'.format(request.data.status_code))
def _enqueue(uri, method="GET", body=None, headers=None, **kwargs):
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 7f949fe..ec7430a 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -61,6 +61,7 @@
PYTHON_VERSION, PY2,
MediaWikiVersion, UnicodeMixin, ComparableMixin, DotReadableDict,
deprecated, deprecate_arg, deprecated_args, issue_deprecation_warning,
+ ModuleDeprecationWrapper as _ModuleDeprecationWrapper,
first_upper, remove_last_args, _NotImplementedWarning,
OrderedDict, Counter,
)
@@ -2306,8 +2307,7 @@
self, step=step, total=total, content=content)
-import pywikibot.tools
-wrapper = pywikibot.tools.ModuleDeprecationWrapper(__name__)
+wrapper = _ModuleDeprecationWrapper(__name__)
wrapper._add_deprecated_attr('ImagePage', FilePage)
--
To view, visit
https://gerrit.wikimedia.org/r/239648
To unsubscribe, visit
https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Id01888d3b9d847927d4adce236153ac4b91a0c72
Gerrit-PatchSet: 8
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Shloub <shloub+wiki(a)gmail.com>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>