jenkins-bot has submitted this change and it was merged.
Change subject: Extract sys.version_info tuple once
......................................................................
Extract sys.version_info tuple once
It is more efficient to check a bool for Python 2 vs 3.
The tools variables PYTHON_VERSION and PY2 allow for consistent
usage. They have not been utilised in this changeset where
sys.version_info is used only during startup and only a few times
during the startup, as there is no significant performance benefit.
Also changed str to its equivalent bytes on Python 2.
Change-Id: I0a29bed4b6239b55f5391ead07ea2fffcaad4855
---
M pywikibot/bot.py
M pywikibot/data/api.py
M pywikibot/tools/__init__.py
M pywikibot/userinterfaces/terminal_interface_base.py
M pywikibot/userinterfaces/terminal_interface_win32.py
M pywikibot/version.py
6 files changed, 35 insertions(+), 31 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index 3091766..ca0afba 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -43,9 +43,9 @@
from pywikibot import config
from pywikibot import daemonize
from pywikibot import version
-from pywikibot.tools import deprecated, deprecated_args
+from pywikibot.tools import deprecated, deprecated_args, PY2
-if sys.version_info[0] > 2:
+if not PY2:
unicode = str
# User interface initialization
@@ -136,7 +136,7 @@
'Arguments for record is not correctly set'
msg = record.args[0]
- if sys.version_info[0] < 3:
+ if PY2:
record.pathname = msg.partition(':')[0]
record.lineno = msg.partition(':')[2].partition(':')[0]
record.module = msg.rpartition('/')[2].rpartition('.')[0]
@@ -181,7 +181,7 @@
"""
strExc = logging.Formatter.formatException(self, ei)
- if sys.version_info[0] < 3 and isinstance(strExc, str):
+ if PY2 and isinstance(strExc, bytes):
return strExc.decode(config.console_encoding) + '\n'
else:
return strExc + '\n'
@@ -1090,7 +1090,7 @@
try:
module = __import__('%s' % module_name)
helpText = module.__doc__
- if sys.version_info[0] < 3 and isinstance(helpText, str):
+ if PY2 and isinstance(helpText, bytes):
helpText = helpText.decode('utf-8')
if hasattr(module, 'docuReplacements'):
for key, value in module.docuReplacements.items():
@@ -1398,7 +1398,7 @@
% self.__class__.__name__)
maxint = 0
- if sys.version_info[0] == 2:
+ if PY2:
maxint = sys.maxint
try:
@@ -1408,7 +1408,7 @@
except SkipPageError as e:
pywikibot.warning('Skipped "{0}" due to: {1}'.format(
page, e.reason))
- if sys.version_info[0] == 2:
+ if PY2:
# Python 2 does not clear the exception and it may seem
# that the generator stopped due to an exception
sys.exc_clear()
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index be9665c..707f148 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -10,7 +10,6 @@
__version__ = '$Id$'
from collections import Container, MutableMapping
-from pywikibot.comms import http
from email.mime.nonmultipart import MIMENonMultipart
import datetime
import hashlib
@@ -30,14 +29,13 @@
import pywikibot
from pywikibot import config, login
-from pywikibot.tools import MediaWikiVersion, deprecated, itergroup, ip
+from pywikibot.tools import MediaWikiVersion, deprecated, itergroup, ip, PY2
from pywikibot.exceptions import (
Server504Error, Server414Error, FatalServerError, Error
)
+from pywikibot.comms import http
-import sys
-
-if sys.version_info[0] > 2:
+if not PY2:
# Subclassing necessary to fix a possible bug of the email package
# in py3: see http://bugs.python.org/issue19003
# The following solution might be removed if/once the bug is fixed,
@@ -1508,7 +1506,7 @@
value.encode('ascii')
# In Python 2, ascii API params should be represented as 'foo'
# rather than u'foo'
- if sys.version_info[0] == 2:
+ if PY2:
value = str(value)
except UnicodeError:
try:
@@ -1609,7 +1607,7 @@
container.attach(submsg)
# strip the headers to get the HTTP message body
- if sys.version_info[0] > 2:
+ if not PY2:
body = container.as_bytes()
else:
body = container.as_string()
diff --git a/pywikibot/tools/__init__.py b/pywikibot/tools/__init__.py
index 7114298..e98efd5 100644
--- a/pywikibot/tools/__init__.py
+++ b/pywikibot/tools/__init__.py
@@ -22,7 +22,10 @@
from distutils.version import Version
from warnings import warn
-if sys.version_info[0] > 2:
+PYTHON_VERSION = sys.version_info[:3]
+PY2 = (PYTHON_VERSION[0] == 2)
+
+if not PY2:
import queue as Queue
basestring = (str,)
unicode = str
@@ -57,7 +60,7 @@
'%s: %s' % (self.__class__.__name__, self.__doc__))
-if sys.version_info < (2, 7):
+if PYTHON_VERSION < (2, 7):
try:
from future.backports.misc import Counter, OrderedDict
except ImportError:
@@ -100,7 +103,7 @@
"""Mixin class to add __str__ method in Python 2 or 3."""
- if sys.version_info[0] > 2:
+ if not PY2:
def __str__(self):
"""Return the unicode representation as the str representation."""
return self.__unicode__()
@@ -162,7 +165,9 @@
def __unicode__(self):
"""Return string representation."""
- if sys.version_info[0] > 2:
+ # TODO: This is more efficient if the PY2 test is done during
+ # class instantiation, and not inside the method.
+ if not PY2:
return repr(self.__dict__)
else:
_content = u', '.join(
@@ -365,7 +370,7 @@
return -1
return 0
- if sys.version_info[0] == 2:
+ if PY2:
__cmp__ = _cmp
@@ -825,7 +830,7 @@
"""
def wrap(wrapped, sub_ver):
"""Wrap in a wrapper when this is below Python version 2.7."""
- if sys.version_info < (2, 7, sub_ver):
+ if PYTHON_VERSION < (2, 7, sub_ver):
return ContextManagerWrapper(wrapped)
else:
return wrapped
diff --git a/pywikibot/userinterfaces/terminal_interface_base.py
b/pywikibot/userinterfaces/terminal_interface_base.py
index c4468e3..2ce3c5d 100755
--- a/pywikibot/userinterfaces/terminal_interface_base.py
+++ b/pywikibot/userinterfaces/terminal_interface_base.py
@@ -19,7 +19,7 @@
import pywikibot
from pywikibot import config
from pywikibot.bot import VERBOSE, INFO, STDOUT, INPUT, WARNING
-from pywikibot.tools import deprecated
+from pywikibot.tools import deprecated, PY2
transliterator = transliteration.transliterator(config.console_encoding)
@@ -124,7 +124,7 @@
line, count = colorTagR.subn('', line)
if count > 0:
line += ' ***'
- if sys.version_info[0] == 2:
+ if PY2:
line = line.encode(self.encoding, 'replace')
targetStream.write(line)
@@ -194,7 +194,7 @@
self._print(text, targetStream)
def _raw_input(self):
- if sys.version_info[0] > 2:
+ if not PY2:
return input()
else:
return raw_input() # noqa
@@ -259,7 +259,7 @@
text = self._raw_input()
except KeyboardInterrupt:
raise pywikibot.QuitKeyboardInterrupt()
- if sys.version_info[0] == 2:
+ if PY2:
text = text.decode(self.encoding)
return text
diff --git a/pywikibot/userinterfaces/terminal_interface_win32.py
b/pywikibot/userinterfaces/terminal_interface_win32.py
index d4f2c1f..a8ff977 100755
--- a/pywikibot/userinterfaces/terminal_interface_win32.py
+++ b/pywikibot/userinterfaces/terminal_interface_win32.py
@@ -10,8 +10,9 @@
__version__ = '$Id$'
import re
-import sys
-from . import terminal_interface_base
+
+from pywikibot.tools import PY2
+from pywikibot.userinterfaces import terminal_interface_base
try:
import ctypes
@@ -76,7 +77,7 @@
if tagM:
# print the text up to the tag.
text_before_tag = text[:tagM.start()]
- if sys.version_info[0] == 2:
+ if PY2:
text_before_tag = text_before_tag.encode(self.encoding,
'replace')
targetStream.write(text_before_tag)
newColor = tagM.group('name')
@@ -94,7 +95,7 @@
ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle,
windowsColors[newColor])
text = text[tagM.end():]
# print the rest of the text
- if sys.version_info[0] == 2:
+ if PY2:
text = text.encode(self.encoding, 'replace')
targetStream.write(text)
# just to be sure, reset the color
diff --git a/pywikibot/version.py b/pywikibot/version.py
index 3fe51f1..45cec8b 100644
--- a/pywikibot/version.py
+++ b/pywikibot/version.py
@@ -32,9 +32,9 @@
import pywikibot
from pywikibot import config2 as config
-from pywikibot.tools import deprecated
+from pywikibot.tools import deprecated, PY2
-if sys.version_info[0] > 2:
+if not PY2:
basestring = (str, )
cache = None
@@ -522,7 +522,7 @@
if '__init__.py' in path:
path = path[0:path.index('__init__.py')]
- if sys.version_info[0] == 2:
+ if PY2:
path = path.decode(sys.getfilesystemencoding())
info['path'] = path
--
To view, visit https://gerrit.wikimedia.org/r/218878
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I0a29bed4b6239b55f5391ead07ea2fffcaad4855
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <[email protected]>
Gerrit-Reviewer: John Vandenberg <[email protected]>
Gerrit-Reviewer: Ladsgroup <[email protected]>
Gerrit-Reviewer: Merlijn van Deen <[email protected]>
Gerrit-Reviewer: XZise <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot <>
_______________________________________________
Pywikibot-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/pywikibot-commits