From 62b0e7eaa22769687df1de8f57374cb0a42bdc4d Mon Sep 17 00:00:00 2001 From: Omer Akram Date: Tue, 21 Jan 2020 18:35:24 +0500 Subject: [PATCH] Py2 removal (#153) * remove all future imports * remove all six imports * change StringIO parent * fix StringIO imports * final removals of six * remove unused vars * remove u keyword for strings * remove u keyword for strings (more) * Make flake8 happy --- docs/conf.py | 12 ++++++------ examples/basic.py | 1 - examples/log_interop_stdlib.py | 1 - examples/log_interop_twisted.py | 1 - examples/multiloop.py | 1 - setup.py | 6 ------ test/_asyncio_test_utils.py | 16 +++++----------- test/test_legacy_logging.py | 1 - test/test_logging.py | 14 ++++++-------- tox.ini | 1 - txaio/__init__.py | 1 - txaio/_common.py | 4 ++-- txaio/_iotype.py | 14 +------------- txaio/_unframework.py | 1 - txaio/_version.py | 2 +- txaio/aio.py | 16 +++++++--------- txaio/interfaces.py | 11 +++-------- txaio/testutil.py | 1 - txaio/tx.py | 29 +++++++++++++---------------- 19 files changed, 44 insertions(+), 89 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index d0a8e09..ecce94c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -94,13 +94,13 @@ def _warn_node(self, msg, node, **kwargs): master_doc = 'contents' # General information about the project. -project = u'txaio' -author = u'Crossbar.io Project' -this_year = u'{0}'.format(time.strftime('%Y')) -if this_year != u'2015': - copyright = u'2015-{0}, Crossbar.io Technologies GmbH'.format(this_year) +project = 'txaio' +author = 'Crossbar.io Project' +this_year = '{0}'.format(time.strftime('%Y')) +if this_year != '2015': + copyright = '2015-{0}, Crossbar.io Technologies GmbH'.format(this_year) else: - copyright = u'2015, Crossbar.io Technologies GmbH' + copyright = '2015, Crossbar.io Technologies GmbH' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the diff --git a/examples/basic.py b/examples/basic.py index e1c3722..1aa816a 100644 --- a/examples/basic.py +++ b/examples/basic.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function import txaio txaio.use_twisted() diff --git a/examples/log_interop_stdlib.py b/examples/log_interop_stdlib.py index a3bcd02..237ed46 100644 --- a/examples/log_interop_stdlib.py +++ b/examples/log_interop_stdlib.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function import sys import logging diff --git a/examples/log_interop_twisted.py b/examples/log_interop_twisted.py index 09c0991..2a7e1b2 100644 --- a/examples/log_interop_twisted.py +++ b/examples/log_interop_twisted.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function import sys import txaio diff --git a/examples/multiloop.py b/examples/multiloop.py index 66e364e..40fe228 100644 --- a/examples/multiloop.py +++ b/examples/multiloop.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function # This example only works with asyncio diff --git a/setup.py b/setup.py index b7bf184..c1b3576 100644 --- a/setup.py +++ b/setup.py @@ -24,15 +24,12 @@ # ############################################################################### -from __future__ import absolute_import import sys import platform from setuptools import setup CPY = platform.python_implementation() == 'CPython' -PY3 = sys.version_info >= (3,) -PY33 = (3, 3) <= sys.version_info < (3, 4) with open('txaio/_version.py') as f: exec(f.read()) # defines __version__ @@ -84,9 +81,6 @@ url='https://github.com/crossbario/txaio', platforms=('Any'), python_requires='>=3.5', - install_requires=[ - 'six' - ], extras_require={ 'twisted': extras_require_twisted, 'asyncio': extras_require_asyncio, diff --git a/test/_asyncio_test_utils.py b/test/_asyncio_test_utils.py index e7438d4..8b8c439 100644 --- a/test/_asyncio_test_utils.py +++ b/test/_asyncio_test_utils.py @@ -55,15 +55,15 @@ def data_file(filename): 'caIssuers': ('http://testca.pythontest.net/testca/pycacert.cer',), 'crlDistributionPoints': ('http://testca.pythontest.net/testca/revocation.crl',), 'issuer': ((('countryName', 'XY'),), - (('organizationName', 'Python Software Foundation CA'),), - (('commonName', 'our-ca-server'),)), + (('organizationName', 'Python Software Foundation CA'),), + (('commonName', 'our-ca-server'),)), 'notAfter': 'Jul 7 14:23:16 2028 GMT', 'notBefore': 'Aug 29 14:23:16 2018 GMT', 'serialNumber': 'CB2D80995A69525C', 'subject': ((('countryName', 'XY'),), - (('localityName', 'Castle Anthrax'),), - (('organizationName', 'Python Software Foundation'),), - (('commonName', 'localhost'),)), + (('localityName', 'Castle Anthrax'),), + (('organizationName', 'Python Software Foundation'),), + (('commonName', 'localhost'),)), 'subjectAltName': (('DNS', 'localhost'),), 'version': 3 } @@ -212,7 +212,6 @@ def server_bind(self): self.server_name = '127.0.0.1' self.server_port = 80 - class UnixWSGIServer(UnixHTTPServer, WSGIServer): request_timeout = 2 @@ -232,22 +231,18 @@ def get_request(self): # to get the tests going return request, ('127.0.0.1', '') - class SilentUnixWSGIServer(UnixWSGIServer): def handle_error(self, request, client_address): pass - class UnixSSLWSGIServer(SSLWSGIServerMixin, SilentUnixWSGIServer): pass - def gen_unix_socket_path(): with tempfile.NamedTemporaryFile() as file: return file.name - @contextlib.contextmanager def unix_socket_path(): path = gen_unix_socket_path() @@ -259,7 +254,6 @@ def unix_socket_path(): except OSError: pass - @contextlib.contextmanager def run_test_unix_server(*, use_ssl=False): with unix_socket_path() as path: diff --git a/test/test_legacy_logging.py b/test/test_legacy_logging.py index 8e63cfe..b19f90c 100644 --- a/test/test_legacy_logging.py +++ b/test/test_legacy_logging.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function import txaio diff --git a/test/test_logging.py b/test/test_logging.py index 528c074..1353608 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -24,13 +24,11 @@ # ############################################################################### -from __future__ import print_function from collections import namedtuple from io import BytesIO, StringIO import os -import six import pytest import txaio @@ -79,7 +77,7 @@ def test_categories(handler, framework): """ logger = txaio.make_logger() - txaio.add_log_categories({"TX100": u"{adjective} {nouns[2]}"}) + txaio.add_log_categories({"TX100": "{adjective} {nouns[2]}"}) # do something a little fancy, with attribute access etc. logger.critical( @@ -100,8 +98,8 @@ def test_categories_subsequent(handler, framework): """ logger = txaio.make_logger() - txaio.add_log_categories({"TX100": u"{adjective} {nouns[2]}"}) - txaio.add_log_categories({"TX100": u"{adjective} {nouns[1]}"}) + txaio.add_log_categories({"TX100": "{adjective} {nouns[2]}"}) + txaio.add_log_categories({"TX100": "{adjective} {nouns[1]}"}) # do something a little fancy, with attribute access etc. logger.critical( @@ -291,7 +289,7 @@ def test_log_converter(handler, framework): from twisted.logger import Logger from txaio.tx import _LogObserver - out = six.StringIO() + out = StringIO() observer = _LogObserver(out) logger = Logger(observer=observer) @@ -344,7 +342,7 @@ def test_txlog_write_text(handler, framework_tx): }) output = out_file.getvalue() - assert u"hi: hello" in output + assert "hi: hello" in output def test_aiolog_write_binary(handler, framework_aio): @@ -384,4 +382,4 @@ def test_aiolog_write_text(handler, framework_aio): })) output = out_file.getvalue() - assert u"hi: hello" in output + assert "hi: hello" in output diff --git a/tox.ini b/tox.ini index 8768317..590d02c 100644 --- a/tox.ini +++ b/tox.ini @@ -12,7 +12,6 @@ envlist = [testenv] deps = - six mock pytest==4.6.9 coverage==4.5.4 diff --git a/txaio/__init__.py b/txaio/__init__.py index 41d5c68..022ff50 100644 --- a/txaio/__init__.py +++ b/txaio/__init__.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import absolute_import from txaio._version import __version__ from txaio.interfaces import IFailedFuture, ILogger diff --git a/txaio/_common.py b/txaio/_common.py index 5a942a4..b2d230f 100644 --- a/txaio/_common.py +++ b/txaio/_common.py @@ -99,9 +99,9 @@ def notify_one_chunk(calls, chunk_size, chunk_delay_ms): else: # done all calls; make sure there were no errors if len(errors): - msg = u"Error(s) processing call_later bucket:\n" + msg = "Error(s) processing call_later bucket:\n" for e in errors: - msg += u"{}\n".format(e) + msg += "{}\n".format(e) raise RuntimeError(msg) # ceil()ing because we want the number of chunks, and a # partial chunk is still a chunk diff --git a/txaio/_iotype.py b/txaio/_iotype.py index ffcf86d..0f54a9b 100644 --- a/txaio/_iotype.py +++ b/txaio/_iotype.py @@ -24,15 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, division - -from six import PY3, PY2 - -if PY3: - unicode = str -else: - unicode = unicode - def guess_stream_needs_encoding(fileobj, default=True): """ @@ -55,7 +46,7 @@ def guess_stream_needs_encoding(fileobj, default=True): if t is bytes: return True - elif t is unicode: + elif t is str: return False except Exception: @@ -64,9 +55,6 @@ def guess_stream_needs_encoding(fileobj, default=True): try: mode = fileobj.mode - if PY2 and mode == "w": - mode = "wb" - if "b" in mode: return True else: diff --git a/txaio/_unframework.py b/txaio/_unframework.py index 7c888b0..49d1267 100644 --- a/txaio/_unframework.py +++ b/txaio/_unframework.py @@ -30,7 +30,6 @@ explicitly by calling .use_twisted() or .use_asyncio() """ -from __future__ import absolute_import, division, print_function from txaio import _Config using_twisted = False diff --git a/txaio/_version.py b/txaio/_version.py index 45a9826..4494728 100644 --- a/txaio/_version.py +++ b/txaio/_version.py @@ -1 +1 @@ -__version__ = u'20.1.1' +__version__ = '20.1.1' diff --git a/txaio/aio.py b/txaio/aio.py index f4aeeb9..8d56b74 100644 --- a/txaio/aio.py +++ b/txaio/aio.py @@ -24,8 +24,7 @@ # ############################################################################### -from __future__ import absolute_import, print_function - +import io import os import sys import time @@ -43,7 +42,6 @@ from txaio import _util from txaio import _Config -import six try: import asyncio @@ -238,7 +236,7 @@ def emit(self, record): if isinstance(record.args, dict): fmt = record.args.get( 'log_format', - record.args.get('log_message', u'') + record.args.get('log_message', '') ) message = fmt.format(**record.args) dt = datetime.fromtimestamp(record.args.get('log_time', 0)) @@ -249,7 +247,7 @@ def emit(self, record): for line in traceback.format_exception(*record.exc_info): message = message + line dt = datetime.fromtimestamp(record.created) - msg = u'{0} {1}{2}'.format( + msg = '{0} {1}{2}'.format( dt.strftime("%Y-%m-%dT%H:%M:%S%z"), message, os.linesep @@ -359,12 +357,12 @@ def failure_message(self, fail): returns a unicode error-message """ try: - return u'{0}: {1}'.format( + return '{0}: {1}'.format( fail._value.__class__.__name__, str(fail._value), ) except Exception: - return u'Failed to produce failure message for "{0}"'.format(fail) + return 'Failed to produce failure message for "{0}"'.format(fail) def failure_traceback(self, fail): """ @@ -379,7 +377,7 @@ def failure_format_traceback(self, fail): returns a string """ try: - f = six.StringIO() + f = io.StringIO() traceback.print_exception( fail._type, fail.value, @@ -388,7 +386,7 @@ def failure_format_traceback(self, fail): ) return f.getvalue() except Exception: - return u"Failed to format failure traceback for '{0}'".format(fail) + return "Failed to format failure traceback for '{0}'".format(fail) def create_future(self, result=_unspecified, error=_unspecified, canceller=_unspecified): if result is not _unspecified and error is not _unspecified: diff --git a/txaio/interfaces.py b/txaio/interfaces.py index 718e50c..c1af839 100644 --- a/txaio/interfaces.py +++ b/txaio/interfaces.py @@ -24,10 +24,8 @@ # ############################################################################### -from __future__ import absolute_import import abc -import six #: all the log-levels that txaio recognizes log_levels = [ @@ -41,8 +39,7 @@ ] -@six.add_metaclass(abc.ABCMeta) -class IBatchedTimer(object): +class IBatchedTimer(abc.ABC): """ Objects created by :met:`txaio.make_batched_timer` implement this interface. @@ -81,8 +78,7 @@ def call_later(self, delay, func, *args, **kw): """ -@six.add_metaclass(abc.ABCMeta) -class ILogger(object): +class ILogger(abc.ABC): """ This defines the methods you can call on the object returned from :meth:`txaio.make_logger` -- although the actual object may have @@ -156,8 +152,7 @@ def trace(self, message, **kwargs): "log a trace-level message" -@six.add_metaclass(abc.ABCMeta) -class IFailedFuture(object): +class IFailedFuture(abc.ABC): """ This defines the interface for a common object encapsulating a failure from either an asyncio task/coroutine or a Twisted diff --git a/txaio/testutil.py b/txaio/testutil.py index a10fb96..dabf1f5 100644 --- a/txaio/testutil.py +++ b/txaio/testutil.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import absolute_import import txaio from contextlib import contextmanager diff --git a/txaio/tx.py b/txaio/tx.py index 3c7323e..735b7a8 100644 --- a/txaio/tx.py +++ b/txaio/tx.py @@ -24,8 +24,7 @@ # ############################################################################### -from __future__ import absolute_import, division, print_function - +import io import os import sys import weakref @@ -46,16 +45,14 @@ from txaio._common import _BatchedTimer from txaio import _util -import six PY3_CORO = False -if six.PY3: - try: - from twisted.internet.defer import ensureDeferred - from asyncio import iscoroutinefunction - PY3_CORO = True - except ImportError: - pass +try: + from twisted.internet.defer import ensureDeferred + from asyncio import iscoroutinefunction + PY3_CORO = True +except ImportError: + pass using_twisted = True using_asyncio = False @@ -99,7 +96,7 @@ class ILogObserver(Interface): def formatTime(t): # noqa dt = datetime.fromtimestamp(t) - return six.u(dt.strftime("%Y-%m-%dT%H:%M:%S%z")) + return dt.strftime("%Y-%m-%dT%H:%M:%S%z") def formatEvent(event): # noqa msg = event['log_format'] @@ -307,7 +304,7 @@ def __call__(self, event): # "Unhandled error in Deferred" -- perhaps this is a Twisted # bug? if event['log_format'] is None: - msg = u'{0} {1}{2}'.format( + msg = '{0} {1}{2}'.format( formatTime(event["log_time"]), failure_format_traceback(event['log_failure']), os.linesep, @@ -319,7 +316,7 @@ def __call__(self, event): # although Logger will already have filtered out unwanted # levels, bare Logger instances from Twisted code won't have. if 'log_level' in event and self._acceptable_level(event['log_level']): - msg = u'{0} {1}{2}'.format( + msg = '{0} {1}{2}'.format( formatTime(event["log_time"]), formatEvent(event), os.linesep, @@ -380,7 +377,7 @@ def failure_message(self, fail): returns a unicode error-message """ try: - return u'{0}: {1}'.format( + return '{0}: {1}'.format( fail.value.__class__.__name__, fail.getErrorMessage(), ) @@ -400,11 +397,11 @@ def failure_format_traceback(self, fail): returns a string """ try: - f = six.StringIO() + f = io.StringIO() fail.printTraceback(file=f) return f.getvalue() except Exception: - return u"Failed to format failure traceback for '{0}'".format(fail) + return "Failed to format failure traceback for '{0}'".format(fail) def create_future(self, result=_unspecified, error=_unspecified, canceller=None): if result is not _unspecified and error is not _unspecified: