summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOmer Katz <omer.drow@gmail.com>2020-07-13 16:58:06 +0300
committerOmer Katz <omer.drow@gmail.com>2020-07-13 16:58:06 +0300
commit7a6e7cc45b9afe799770313a66c4211d1986ff30 (patch)
tree189c7fa2e7ca9835e14975093c12b7e5d3d8213b
parent016f4accb634ebc3eb8fc66741f23552e5966ea7 (diff)
downloadkombu-7a6e7cc45b9afe799770313a66c4211d1986ff30.tar.gz
pyupgrade
-rw-r--r--docs/conf.py3
-rw-r--r--examples/complete_receive.py7
-rw-r--r--examples/complete_send.py1
-rw-r--r--examples/experimental/async_consume.py3
-rw-r--r--examples/hello_consumer.py4
-rw-r--r--examples/hello_publisher.py6
-rw-r--r--examples/memory_transport.py2
-rw-r--r--examples/rpc-tut6/rpc_client.py5
-rw-r--r--examples/rpc-tut6/rpc_server.py3
-rw-r--r--examples/simple_eventlet_receive.py1
-rw-r--r--examples/simple_eventlet_send.py3
-rw-r--r--examples/simple_receive.py1
-rw-r--r--examples/simple_send.py1
-rw-r--r--examples/simple_task_queue/client.py2
-rw-r--r--examples/simple_task_queue/queues.py2
-rw-r--r--examples/simple_task_queue/tasks.py5
-rw-r--r--examples/simple_task_queue/worker.py2
-rw-r--r--kombu/__init__.py1
-rw-r--r--kombu/abstract.py9
-rw-r--r--kombu/asynchronous/__init__.py2
-rw-r--r--kombu/asynchronous/aws/__init__.py4
-rw-r--r--kombu/asynchronous/aws/connection.py12
-rw-r--r--kombu/asynchronous/aws/ext.py4
-rw-r--r--kombu/asynchronous/aws/sqs/connection.py24
-rw-r--r--kombu/asynchronous/aws/sqs/ext.py2
-rw-r--r--kombu/asynchronous/aws/sqs/message.py2
-rw-r--r--kombu/asynchronous/aws/sqs/queue.py2
-rw-r--r--kombu/asynchronous/debug.py9
-rw-r--r--kombu/asynchronous/http/__init__.py2
-rw-r--r--kombu/asynchronous/http/base.py7
-rw-r--r--kombu/asynchronous/http/curl.py9
-rw-r--r--kombu/asynchronous/hub.py6
-rw-r--r--kombu/asynchronous/semaphore.py8
-rw-r--r--kombu/asynchronous/timer.py8
-rw-r--r--kombu/clocks.py5
-rw-r--r--kombu/common.py15
-rw-r--r--kombu/compat.py13
-rw-r--r--kombu/compression.py1
-rw-r--r--kombu/connection.py19
-rw-r--r--kombu/entity.py21
-rw-r--r--kombu/exceptions.py3
-rw-r--r--kombu/five.py2
-rw-r--r--kombu/log.py5
-rw-r--r--kombu/matcher.py9
-rw-r--r--kombu/message.py5
-rw-r--r--kombu/messaging.py9
-rw-r--r--kombu/mixins.py6
-rw-r--r--kombu/pidbox.py11
-rw-r--r--kombu/pools.py5
-rw-r--r--kombu/resource.py13
-rw-r--r--kombu/serialization.py13
-rw-r--r--kombu/simple.py5
-rw-r--r--kombu/transport/SLMQ.py15
-rw-r--r--kombu/transport/SQS.py21
-rw-r--r--kombu/transport/__init__.py5
-rw-r--r--kombu/transport/azureservicebus.py5
-rw-r--r--kombu/transport/azurestoragequeues.py7
-rw-r--r--kombu/transport/base.py7
-rw-r--r--kombu/transport/consul.py21
-rw-r--r--kombu/transport/etcd.py23
-rw-r--r--kombu/transport/filesystem.py15
-rw-r--r--kombu/transport/librabbitmq.py3
-rw-r--r--kombu/transport/memory.py3
-rw-r--r--kombu/transport/mongodb.py9
-rw-r--r--kombu/transport/pyamqp.py5
-rw-r--r--kombu/transport/pyro.py9
-rw-r--r--kombu/transport/qpid.py15
-rw-r--r--kombu/transport/redis.py27
-rw-r--r--kombu/transport/sqlalchemy/__init__.py3
-rw-r--r--kombu/transport/sqlalchemy/models.py7
-rw-r--r--kombu/transport/virtual/__init__.py2
-rw-r--r--kombu/transport/virtual/base.py23
-rw-r--r--kombu/transport/virtual/exchange.py3
-rw-r--r--kombu/transport/zookeeper.py7
-rw-r--r--kombu/utils/__init__.py1
-rw-r--r--kombu/utils/amq_manager.py3
-rw-r--r--kombu/utils/collections.py1
-rw-r--r--kombu/utils/compat.py1
-rw-r--r--kombu/utils/debug.py7
-rw-r--r--kombu/utils/div.py5
-rw-r--r--kombu/utils/encoding.py6
-rw-r--r--kombu/utils/eventio.py25
-rw-r--r--kombu/utils/functional.py9
-rw-r--r--kombu/utils/imports.py3
-rw-r--r--kombu/utils/json.py6
-rw-r--r--kombu/utils/limits.py3
-rw-r--r--kombu/utils/objects.py3
-rw-r--r--kombu/utils/scheduling.py5
-rw-r--r--kombu/utils/text.py2
-rw-r--r--kombu/utils/time.py1
-rw-r--r--kombu/utils/url.py3
-rw-r--r--kombu/utils/uuid.py1
-rw-r--r--setup.py1
-rw-r--r--t/integration/__init__.py2
-rw-r--r--t/integration/common.py18
-rw-r--r--t/integration/test_py_amqp.py6
-rw-r--r--t/integration/test_redis.py4
-rw-r--r--t/mocks.py10
-rw-r--r--t/unit/__init__.py1
-rw-r--r--t/unit/asynchronous/aws/case.py5
-rw-r--r--t/unit/asynchronous/aws/sqs/test_connection.py3
-rw-r--r--t/unit/asynchronous/aws/sqs/test_queue.py5
-rw-r--r--t/unit/asynchronous/aws/test_aws.py3
-rw-r--r--t/unit/asynchronous/aws/test_connection.py3
-rw-r--r--t/unit/asynchronous/http/test_curl.py3
-rw-r--r--t/unit/asynchronous/http/test_http.py2
-rw-r--r--t/unit/asynchronous/test_hub.py6
-rw-r--r--t/unit/asynchronous/test_semaphore.py2
-rw-r--r--t/unit/asynchronous/test_timer.py2
-rw-r--r--t/unit/conftest.py4
-rw-r--r--t/unit/test_clocks.py2
-rw-r--r--t/unit/test_common.py6
-rw-r--r--t/unit/test_compat.py9
-rw-r--r--t/unit/test_compression.py2
-rw-r--r--t/unit/test_connection.py2
-rw-r--r--t/unit/test_entity.py6
-rw-r--r--t/unit/test_exceptions.py2
-rw-r--r--t/unit/test_log.py2
-rw-r--r--t/unit/test_matcher.py4
-rw-r--r--t/unit/test_message.py2
-rw-r--r--t/unit/test_messaging.py4
-rw-r--r--t/unit/test_mixins.py4
-rw-r--r--t/unit/test_pidbox.py2
-rw-r--r--t/unit/test_pools.py2
-rw-r--r--t/unit/test_serialization.py6
-rw-r--r--t/unit/test_simple.py8
-rw-r--r--t/unit/transport/test_SQS.py15
-rw-r--r--t/unit/transport/test_azureservicebus.py8
-rw-r--r--t/unit/transport/test_base.py2
-rw-r--r--t/unit/transport/test_consul.py2
-rw-r--r--t/unit/transport/test_etcd.py2
-rw-r--r--t/unit/transport/test_filesystem.py2
-rw-r--r--t/unit/transport/test_librabbitmq.py2
-rw-r--r--t/unit/transport/test_memory.py4
-rw-r--r--t/unit/transport/test_mongodb.py2
-rw-r--r--t/unit/transport/test_pyamqp.py6
-rw-r--r--t/unit/transport/test_pyro.py4
-rw-r--r--t/unit/transport/test_qpid.py48
-rw-r--r--t/unit/transport/test_redis.py28
-rw-r--r--t/unit/transport/test_sqlalchemy.py2
-rw-r--r--t/unit/transport/test_transport.py2
-rw-r--r--t/unit/transport/test_zookeeper.py2
-rw-r--r--t/unit/transport/virtual/test_base.py12
-rw-r--r--t/unit/transport/virtual/test_exchange.py2
-rw-r--r--t/unit/utils/test_amq_manager.py2
-rw-r--r--t/unit/utils/test_compat.py2
-rw-r--r--t/unit/utils/test_debug.py2
-rw-r--r--t/unit/utils/test_div.py2
-rw-r--r--t/unit/utils/test_encoding.py11
-rw-r--r--t/unit/utils/test_functional.py4
-rw-r--r--t/unit/utils/test_imports.py2
-rw-r--r--t/unit/utils/test_json.py6
-rw-r--r--t/unit/utils/test_objects.py6
-rw-r--r--t/unit/utils/test_scheduling.py2
-rw-r--r--t/unit/utils/test_time.py2
-rw-r--r--t/unit/utils/test_url.py2
-rw-r--r--t/unit/utils/test_utils.py2
-rw-r--r--t/unit/utils/test_uuid.py2
158 files changed, 360 insertions, 617 deletions
diff --git a/docs/conf.py b/docs/conf.py
index 88af9eb8..4f9f44d8 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
from sphinx_celery import conf
globals().update(conf.build_config(
diff --git a/examples/complete_receive.py b/examples/complete_receive.py
index e9f2024b..f122262a 100644
--- a/examples/complete_receive.py
+++ b/examples/complete_receive.py
@@ -3,7 +3,6 @@ Example of simple consumer that waits for a single message, acknowledges it
and exits.
"""
-from __future__ import absolute_import, unicode_literals, print_function
from pprint import pformat
@@ -21,9 +20,9 @@ def pretty(obj):
#: This is the callback applied when a message is received.
def handle_message(body, message):
- print('Received message: {0!r}'.format(body))
- print(' properties:\n{0}'.format(pretty(message.properties)))
- print(' delivery_info:\n{0}'.format(pretty(message.delivery_info)))
+ print(f'Received message: {body!r}')
+ print(' properties:\n{}'.format(pretty(message.properties)))
+ print(' delivery_info:\n{}'.format(pretty(message.delivery_info)))
message.ack()
#: Create a connection and a channel.
diff --git a/examples/complete_send.py b/examples/complete_send.py
index 6c33a820..90bd3f9e 100644
--- a/examples/complete_send.py
+++ b/examples/complete_send.py
@@ -5,7 +5,6 @@ Example producer that sends a single message and exits.
You can use `complete_receive.py` to receive the message sent.
"""
-from __future__ import absolute_import, unicode_literals
from kombu import Connection, Producer, Exchange, Queue
diff --git a/examples/experimental/async_consume.py b/examples/experimental/async_consume.py
index b794687e..aebb974b 100644
--- a/examples/experimental/async_consume.py
+++ b/examples/experimental/async_consume.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-from __future__ import absolute_import, unicode_literals
from kombu import Connection, Exchange, Queue, Producer, Consumer
from kombu.asynchronous import Hub
@@ -16,7 +15,7 @@ def send_message(conn):
def on_message(message):
- print('received: {0!r}'.format(message.body))
+ print(f'received: {message.body!r}')
message.ack()
hub.stop() # <-- exit after one message
diff --git a/examples/hello_consumer.py b/examples/hello_consumer.py
index 71f40f13..e633e02d 100644
--- a/examples/hello_consumer.py
+++ b/examples/hello_consumer.py
@@ -1,11 +1,9 @@
-from __future__ import absolute_import, unicode_literals, print_function
-
from kombu import Connection # noqa
with Connection('amqp://guest:guest@localhost:5672//') as conn:
simple_queue = conn.SimpleQueue('simple_queue')
message = simple_queue.get(block=True, timeout=1)
- print('Received: {0}'.format(message.payload))
+ print(f'Received: {message.payload}')
message.ack()
simple_queue.close()
diff --git a/examples/hello_publisher.py b/examples/hello_publisher.py
index e6b07361..d6a49048 100644
--- a/examples/hello_publisher.py
+++ b/examples/hello_publisher.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import datetime
from kombu import Connection
@@ -7,7 +5,7 @@ from kombu import Connection
with Connection('amqp://guest:guest@localhost:5672//') as conn:
simple_queue = conn.SimpleQueue('simple_queue')
- message = 'helloworld, sent at {0}'.format(datetime.datetime.today())
+ message = f'helloworld, sent at {datetime.datetime.today()}'
simple_queue.put(message)
- print('Sent: {0}'.format(message))
+ print(f'Sent: {message}')
simple_queue.close()
diff --git a/examples/memory_transport.py b/examples/memory_transport.py
index f0b43940..662c94a0 100644
--- a/examples/memory_transport.py
+++ b/examples/memory_transport.py
@@ -11,7 +11,7 @@ task_queues = [video_queue]
def handle_message(body, message):
- print("%s RECEIVED MESSAGE: %r" % (time.time(), body))
+ print(f"{time.time()} RECEIVED MESSAGE: {body!r}")
message.ack()
diff --git a/examples/rpc-tut6/rpc_client.py b/examples/rpc-tut6/rpc_client.py
index bf058f56..6ed5833f 100644
--- a/examples/rpc-tut6/rpc_client.py
+++ b/examples/rpc-tut6/rpc_client.py
@@ -1,10 +1,9 @@
#!/usr/bin/env python
-from __future__ import absolute_import, unicode_literals
from kombu import Connection, Producer, Consumer, Queue, uuid
-class FibonacciRpcClient(object):
+class FibonacciRpcClient:
def __init__(self, connection):
self.connection = connection
@@ -39,7 +38,7 @@ def main(broker_url):
fibonacci_rpc = FibonacciRpcClient(connection)
print(' [x] Requesting fib(30)')
response = fibonacci_rpc.call(30)
- print(' [.] Got {0!r}'.format(response))
+ print(f' [.] Got {response!r}')
if __name__ == '__main__':
diff --git a/examples/rpc-tut6/rpc_server.py b/examples/rpc-tut6/rpc_server.py
index bb64726b..761630ca 100644
--- a/examples/rpc-tut6/rpc_server.py
+++ b/examples/rpc-tut6/rpc_server.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-from __future__ import absolute_import, unicode_literals
from kombu import Connection, Queue
from kombu.mixins import ConsumerProducerMixin
@@ -31,7 +30,7 @@ class Worker(ConsumerProducerMixin):
def on_request(self, message):
n = message.payload['n']
- print(' [.] fib({0})'.format(n))
+ print(f' [.] fib({n})')
result = fib(n)
self.producer.publish(
diff --git a/examples/simple_eventlet_receive.py b/examples/simple_eventlet_receive.py
index 8d977cc1..18a3f6bb 100644
--- a/examples/simple_eventlet_receive.py
+++ b/examples/simple_eventlet_receive.py
@@ -6,7 +6,6 @@ You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
-from __future__ import absolute_import, unicode_literals
import eventlet
diff --git a/examples/simple_eventlet_send.py b/examples/simple_eventlet_send.py
index 2998fe37..9a753e7a 100644
--- a/examples/simple_eventlet_send.py
+++ b/examples/simple_eventlet_send.py
@@ -6,7 +6,6 @@ You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
-from __future__ import absolute_import, unicode_literals
import eventlet
@@ -30,7 +29,7 @@ def send_many(n):
with connection.SimpleQueue('kombu_demo') as queue:
def send_message(i):
- queue.put({'hello': 'world%s' % (i,)})
+ queue.put({'hello': f'world{i}'})
pool = eventlet.GreenPool(10)
for i in range(n):
diff --git a/examples/simple_receive.py b/examples/simple_receive.py
index a534ff70..90c2d0ae 100644
--- a/examples/simple_receive.py
+++ b/examples/simple_receive.py
@@ -2,7 +2,6 @@
Example receiving a message using the SimpleQueue interface.
"""
-from __future__ import absolute_import, unicode_literals
from kombu import Connection
diff --git a/examples/simple_send.py b/examples/simple_send.py
index c70d87a6..d2eacea4 100644
--- a/examples/simple_send.py
+++ b/examples/simple_send.py
@@ -6,7 +6,6 @@ You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
-from __future__ import absolute_import, unicode_literals
from kombu import Connection
diff --git a/examples/simple_task_queue/client.py b/examples/simple_task_queue/client.py
index ec348cf5..e19b9476 100644
--- a/examples/simple_task_queue/client.py
+++ b/examples/simple_task_queue/client.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.pools import producers
from .queues import task_exchange
diff --git a/examples/simple_task_queue/queues.py b/examples/simple_task_queue/queues.py
index ccdc3f2c..602c2b0e 100644
--- a/examples/simple_task_queue/queues.py
+++ b/examples/simple_task_queue/queues.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu import Exchange, Queue
task_exchange = Exchange('tasks', type='direct')
diff --git a/examples/simple_task_queue/tasks.py b/examples/simple_task_queue/tasks.py
index 99258ce3..2810f7a8 100644
--- a/examples/simple_task_queue/tasks.py
+++ b/examples/simple_task_queue/tasks.py
@@ -1,5 +1,2 @@
-from __future__ import absolute_import, unicode_literals
-
-
def hello_task(who='world'):
- print('Hello {0}'.format(who))
+ print(f'Hello {who}')
diff --git a/examples/simple_task_queue/worker.py b/examples/simple_task_queue/worker.py
index bd2dd7f8..14064ccf 100644
--- a/examples/simple_task_queue/worker.py
+++ b/examples/simple_task_queue/worker.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.mixins import ConsumerMixin
from kombu.log import get_logger
from kombu.utils.functional import reprcall
diff --git a/kombu/__init__.py b/kombu/__init__.py
index ed48fff6..e650e2a1 100644
--- a/kombu/__init__.py
+++ b/kombu/__init__.py
@@ -1,5 +1,4 @@
"""Messaging library for Python."""
-from __future__ import absolute_import, unicode_literals
import os
import re
diff --git a/kombu/abstract.py b/kombu/abstract.py
index 5d6c1fe4..d1616da7 100644
--- a/kombu/abstract.py
+++ b/kombu/abstract.py
@@ -1,5 +1,4 @@
"""Object utilities."""
-from __future__ import absolute_import, unicode_literals
from copy import copy
@@ -19,7 +18,7 @@ def _any(v):
return v
-class Object(object):
+class Object:
"""Common base class.
Supports automatic kwargs->attributes handling, and cloning.
@@ -100,9 +99,9 @@ class MaybeChannelBound(Object):
def _repr_entity(self, item=''):
item = item or type(self).__name__
if self.is_bound:
- return '<{0} bound to chan:{1}>'.format(
+ return '<{} bound to chan:{}>'.format(
item or type(self).__name__, self.channel.channel_id)
- return '<unbound {0}>'.format(item)
+ return f'<unbound {item}>'
@property
def is_bound(self):
@@ -115,7 +114,7 @@ class MaybeChannelBound(Object):
channel = self._channel
if channel is None:
raise NotBoundError(
- "Can't call method on {0} not bound to a channel".format(
+ "Can't call method on {} not bound to a channel".format(
type(self).__name__))
if isinstance(channel, ChannelPromise):
channel = self._channel = channel()
diff --git a/kombu/asynchronous/__init__.py b/kombu/asynchronous/__init__.py
index 8d078d07..4028068f 100644
--- a/kombu/asynchronous/__init__.py
+++ b/kombu/asynchronous/__init__.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Event loop."""
-from __future__ import absolute_import, unicode_literals
from .hub import Hub, get_event_loop, set_event_loop
diff --git a/kombu/asynchronous/aws/__init__.py b/kombu/asynchronous/aws/__init__.py
index 0bdc37af..d8423c23 100644
--- a/kombu/asynchronous/aws/__init__.py
+++ b/kombu/asynchronous/aws/__init__.py
@@ -1,7 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
-
def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""Return async connection to Amazon SQS."""
from .sqs.connection import AsyncSQSConnection
diff --git a/kombu/asynchronous/aws/connection.py b/kombu/asynchronous/aws/connection.py
index 36a1c29e..2c5dc6f1 100644
--- a/kombu/asynchronous/aws/connection.py
+++ b/kombu/asynchronous/aws/connection.py
@@ -1,6 +1,4 @@
-# * coding: utf8 *
"""Amazon AWS Connection."""
-from __future__ import absolute_import, unicode_literals
from vine import promise, transform
@@ -26,7 +24,7 @@ except ImportError: # pragma: no cover
# py2
def message_from_headers(hdr): # noqa
return io.BytesIO(b'\r\n'.join(
- b'{0}: {1}'.format(*h) for h in hdr
+ b'{}: {}'.format(*h) for h in hdr
))
__all__ = (
@@ -35,7 +33,7 @@ __all__ = (
@python_2_unicode_compatible
-class AsyncHTTPResponse(object):
+class AsyncHTTPResponse:
"""Async HTTP Response."""
def __init__(self, response):
@@ -73,7 +71,7 @@ class AsyncHTTPResponse(object):
@python_2_unicode_compatible
-class AsyncHTTPSConnection(object):
+class AsyncHTTPSConnection:
"""Async HTTP Connection."""
Request = Request
@@ -140,10 +138,10 @@ class AsyncHTTPSConnection(object):
self.body = data
def __repr__(self):
- return '<AsyncHTTPConnection: {0!r}>'.format(self.getrequest())
+ return f'<AsyncHTTPConnection: {self.getrequest()!r}>'
-class AsyncConnection(object):
+class AsyncConnection:
"""Async AWS Connection."""
def __init__(self, sqs_connection, http_client=None, **kwargs): # noqa
diff --git a/kombu/asynchronous/aws/ext.py b/kombu/asynchronous/aws/ext.py
index 8c962df9..2dedc812 100644
--- a/kombu/asynchronous/aws/ext.py
+++ b/kombu/asynchronous/aws/ext.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Amazon boto3 interface."""
-from __future__ import absolute_import, unicode_literals
try:
import boto3
@@ -10,7 +8,7 @@ try:
except ImportError:
boto3 = None
- class _void(object):
+ class _void:
pass
class BotoCoreError(Exception):
diff --git a/kombu/asynchronous/aws/sqs/connection.py b/kombu/asynchronous/aws/sqs/connection.py
index e5e440e4..1235fe16 100644
--- a/kombu/asynchronous/aws/sqs/connection.py
+++ b/kombu/asynchronous/aws/sqs/connection.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Amazon SQS Connection."""
-from __future__ import absolute_import, unicode_literals
from vine import transform
@@ -85,10 +83,10 @@ class AsyncSQSConnection(AsyncAWSQueryConnection):
def delete_message_batch(self, queue, messages, callback=None):
params = {}
for i, m in enumerate(messages):
- prefix = 'DeleteMessageBatchRequestEntry.{0}'.format(i + 1)
+ prefix = 'DeleteMessageBatchRequestEntry.{}'.format(i + 1)
params.update({
- '{0}.Id'.format(prefix): m.id,
- '{0}.ReceiptHandle'.format(prefix): m.receipt_handle,
+ f'{prefix}.Id': m.id,
+ f'{prefix}.ReceiptHandle': m.receipt_handle,
})
return self.get_object(
'DeleteMessageBatch', params, queue.id,
@@ -115,11 +113,11 @@ class AsyncSQSConnection(AsyncAWSQueryConnection):
def send_message_batch(self, queue, messages, callback=None):
params = {}
for i, msg in enumerate(messages):
- prefix = 'SendMessageBatchRequestEntry.{0}'.format(i + 1)
+ prefix = 'SendMessageBatchRequestEntry.{}'.format(i + 1)
params.update({
- '{0}.Id'.format(prefix): msg[0],
- '{0}.MessageBody'.format(prefix): msg[1],
- '{0}.DelaySeconds'.format(prefix): msg[2],
+ f'{prefix}.Id': msg[0],
+ f'{prefix}.MessageBody': msg[1],
+ f'{prefix}.DelaySeconds': msg[2],
})
return self.get_object(
'SendMessageBatch', params, queue.id,
@@ -138,11 +136,11 @@ class AsyncSQSConnection(AsyncAWSQueryConnection):
def change_message_visibility_batch(self, queue, messages, callback=None):
params = {}
for i, t in enumerate(messages):
- pre = 'ChangeMessageVisibilityBatchRequestEntry.{0}'.format(i + 1)
+ pre = 'ChangeMessageVisibilityBatchRequestEntry.{}'.format(i + 1)
params.update({
- '{0}.Id'.format(pre): t[0].id,
- '{0}.ReceiptHandle'.format(pre): t[0].receipt_handle,
- '{0}.VisibilityTimeout'.format(pre): t[1],
+ f'{pre}.Id': t[0].id,
+ f'{pre}.ReceiptHandle': t[0].receipt_handle,
+ f'{pre}.VisibilityTimeout': t[1],
})
return self.get_object(
'ChangeMessageVisibilityBatch', params, queue.id,
diff --git a/kombu/asynchronous/aws/sqs/ext.py b/kombu/asynchronous/aws/sqs/ext.py
index 09fdf1a1..f6630936 100644
--- a/kombu/asynchronous/aws/sqs/ext.py
+++ b/kombu/asynchronous/aws/sqs/ext.py
@@ -1,7 +1,5 @@
-# -*- coding: utf-8 -*-
"""Amazon SQS boto3 interface."""
-from __future__ import absolute_import, unicode_literals
try:
import boto3
diff --git a/kombu/asynchronous/aws/sqs/message.py b/kombu/asynchronous/aws/sqs/message.py
index 28ca6db6..9425ff2d 100644
--- a/kombu/asynchronous/aws/sqs/message.py
+++ b/kombu/asynchronous/aws/sqs/message.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Amazon SQS message implementation."""
-from __future__ import absolute_import, unicode_literals
import base64
diff --git a/kombu/asynchronous/aws/sqs/queue.py b/kombu/asynchronous/aws/sqs/queue.py
index c0f8c0f3..50b0be55 100644
--- a/kombu/asynchronous/aws/sqs/queue.py
+++ b/kombu/asynchronous/aws/sqs/queue.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Amazon SQS queue implementation."""
-from __future__ import absolute_import, unicode_literals
from vine import transform
diff --git a/kombu/asynchronous/debug.py b/kombu/asynchronous/debug.py
index 0e5ffbe0..002c8ec9 100644
--- a/kombu/asynchronous/debug.py
+++ b/kombu/asynchronous/debug.py
@@ -1,5 +1,4 @@
"""Event-loop debugging tools."""
-from __future__ import absolute_import, unicode_literals
from kombu.five import items, string_t
from kombu.utils.eventio import READ, WRITE, ERR
@@ -8,7 +7,7 @@ from kombu.utils.functional import reprcall
def repr_flag(flag):
"""Return description of event loop flag."""
- return '{0}{1}{2}'.format('R' if flag & READ else '',
+ return '{}{}{}'.format('R' if flag & READ else '',
'W' if flag & WRITE else '',
'!' if flag & ERR else '')
@@ -32,7 +31,7 @@ def repr_active(h):
def repr_events(h, events):
"""Return description of events returned by poll."""
return ', '.join(
- '{0}({1})->{2}'.format(
+ '{}({})->{}'.format(
_rcb(callback_for(h, fd, fl, '(GONE)')), fd,
repr_flag(fl),
)
@@ -42,13 +41,13 @@ def repr_events(h, events):
def repr_readers(h):
"""Return description of pending readers."""
- return ['({0}){1}->{2}'.format(fd, _rcb(cb), repr_flag(READ | ERR))
+ return ['({}){}->{}'.format(fd, _rcb(cb), repr_flag(READ | ERR))
for fd, cb in items(h.readers)]
def repr_writers(h):
"""Return description of pending writers."""
- return ['({0}){1}->{2}'.format(fd, _rcb(cb), repr_flag(WRITE))
+ return ['({}){}->{}'.format(fd, _rcb(cb), repr_flag(WRITE))
for fd, cb in items(h.writers)]
diff --git a/kombu/asynchronous/http/__init__.py b/kombu/asynchronous/http/__init__.py
index eb586474..e776977d 100644
--- a/kombu/asynchronous/http/__init__.py
+++ b/kombu/asynchronous/http/__init__.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.asynchronous import get_event_loop
from .base import Request, Headers, Response
diff --git a/kombu/asynchronous/http/base.py b/kombu/asynchronous/http/base.py
index c7e34531..894f13f6 100644
--- a/kombu/asynchronous/http/base.py
+++ b/kombu/asynchronous/http/base.py
@@ -1,5 +1,4 @@
"""Base async HTTP client implementation."""
-from __future__ import absolute_import, unicode_literals
import sys
@@ -41,7 +40,7 @@ class Headers(dict):
@Thenable.register
@python_2_unicode_compatible
-class Request(object):
+class Request:
"""A HTTP Request.
Arguments:
@@ -136,7 +135,7 @@ class Request(object):
return '<Request: {0.method} {0.url} {0.body}>'.format(self)
-class Response(object):
+class Response:
"""HTTP Response.
Arguments:
@@ -230,7 +229,7 @@ def header_parser(keyt=normalize_header):
headers[key] = value.strip()
-class BaseClient(object):
+class BaseClient:
Headers = Headers
Request = Request
Response = Response
diff --git a/kombu/asynchronous/http/curl.py b/kombu/asynchronous/http/curl.py
index cdfc84bb..f4cdf523 100644
--- a/kombu/asynchronous/http/curl.py
+++ b/kombu/asynchronous/http/curl.py
@@ -1,5 +1,4 @@
"""HTTP Client using pyCurl."""
-from __future__ import absolute_import, unicode_literals
from collections import deque
from functools import partial
@@ -42,7 +41,7 @@ class CurlClient(BaseClient):
if pycurl is None:
raise ImportError('The curl client requires the pycurl library.')
hub = hub or get_event_loop()
- super(CurlClient, self).__init__(hub)
+ super().__init__(hub)
self.max_clients = max_clients
self._multi = pycurl.CurlMulti()
@@ -203,7 +202,7 @@ class CurlClient(BaseClient):
setopt(
_pycurl.HTTPHEADER,
- ['{0}: {1}'.format(*h) for h in items(request.headers)],
+ ['{}: {}'.format(*h) for h in items(request.headers)],
)
setopt(
@@ -231,7 +230,7 @@ class CurlClient(BaseClient):
setopt(_pycurl.PROXY, request.proxy_host)
setopt(_pycurl.PROXYPORT, request.proxy_port)
if request.proxy_username:
- setopt(_pycurl.PROXYUSERPWD, '{0}:{1}'.format(
+ setopt(_pycurl.PROXYUSERPWD, '{}:{}'.format(
request.proxy_username, request.proxy_password or ''))
else:
setopt(_pycurl.PROXY, '')
@@ -276,7 +275,7 @@ class CurlClient(BaseClient):
'digest': _pycurl.HTTPAUTH_DIGEST
}[request.auth_mode or 'basic']
setopt(_pycurl.HTTPAUTH, auth_mode)
- userpwd = '{0}:{1}'.format(
+ userpwd = '{}:{}'.format(
request.auth_username, request.auth_password or '',
)
setopt(_pycurl.USERPWD, userpwd)
diff --git a/kombu/asynchronous/hub.py b/kombu/asynchronous/hub.py
index e49afeab..7f761796 100644
--- a/kombu/asynchronous/hub.py
+++ b/kombu/asynchronous/hub.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Event loop implementation."""
-from __future__ import absolute_import, unicode_literals
import errno
from contextlib import contextmanager
@@ -52,7 +50,7 @@ def set_event_loop(loop):
@python_2_unicode_compatible
-class Hub(object):
+class Hub:
"""Event loop object.
Arguments:
@@ -128,7 +126,7 @@ class Hub(object):
self.call_soon(_raise_stop_error)
def __repr__(self):
- return '<Hub@{0:#x}: R:{1} W:{2}>'.format(
+ return '<Hub@{:#x}: R:{} W:{}>'.format(
id(self), len(self.readers), len(self.writers),
)
diff --git a/kombu/asynchronous/semaphore.py b/kombu/asynchronous/semaphore.py
index 00b73436..270700a8 100644
--- a/kombu/asynchronous/semaphore.py
+++ b/kombu/asynchronous/semaphore.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Semaphores and concurrency primitives."""
-from __future__ import absolute_import, unicode_literals
from collections import deque
@@ -10,7 +8,7 @@ __all__ = ('DummyLock', 'LaxBoundedSemaphore')
@python_2_unicode_compatible
-class LaxBoundedSemaphore(object):
+class LaxBoundedSemaphore:
"""Asynchronous Bounded Semaphore.
Lax means that the value will stay within the specified
@@ -93,12 +91,12 @@ class LaxBoundedSemaphore(object):
self.value = self.initial_value
def __repr__(self):
- return '<{0} at {1:#x} value:{2} waiting:{3}>'.format(
+ return '<{} at {:#x} value:{} waiting:{}>'.format(
self.__class__.__name__, id(self), self.value, len(self._waiting),
)
-class DummyLock(object):
+class DummyLock:
"""Pretending to be a lock."""
def __enter__(self):
diff --git a/kombu/asynchronous/timer.py b/kombu/asynchronous/timer.py
index 5eda12f3..d159ab15 100644
--- a/kombu/asynchronous/timer.py
+++ b/kombu/asynchronous/timer.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Timer scheduling Python callbacks."""
-from __future__ import absolute_import, unicode_literals
import heapq
import sys
@@ -47,7 +45,7 @@ def to_timestamp(d, default_timezone=utc, time=monotonic):
@total_ordering
@python_2_unicode_compatible
-class Entry(object):
+class Entry:
"""Schedule Entry."""
if not IS_PYPY: # pragma: no cover
@@ -74,7 +72,7 @@ class Entry(object):
pass
def __repr__(self):
- return '<TimerEntry: {0}(*{1!r}, **{2!r})'.format(
+ return '<TimerEntry: {}(*{!r}, **{!r})'.format(
self.fun.__name__, self.args, self.kwargs)
# must not use hash() to order entries
@@ -90,7 +88,7 @@ class Entry(object):
self.canceled = value
-class Timer(object):
+class Timer:
"""Async timer implementation."""
Entry = Entry
diff --git a/kombu/clocks.py b/kombu/clocks.py
index 0e086637..44740ba7 100644
--- a/kombu/clocks.py
+++ b/kombu/clocks.py
@@ -1,5 +1,4 @@
"""Logical Clocks and Synchronization."""
-from __future__ import absolute_import, unicode_literals
from threading import Lock
from itertools import islice
@@ -65,7 +64,7 @@ class timetuple(tuple):
@python_2_unicode_compatible
-class LamportClock(object):
+class LamportClock:
"""Lamport's logical clock.
From Wikipedia:
@@ -149,4 +148,4 @@ class LamportClock(object):
return str(self.value)
def __repr__(self):
- return '<LamportClock: {0.value}>'.format(self)
+ return f'<LamportClock: {self.value}>'
diff --git a/kombu/common.py b/kombu/common.py
index 307a8cec..17d1f5d8 100644
--- a/kombu/common.py
+++ b/kombu/common.py
@@ -1,5 +1,4 @@
"""Common Utilities."""
-from __future__ import absolute_import, unicode_literals
import os
import socket
@@ -48,7 +47,7 @@ def get_node_id():
def generate_oid(node_id, process_id, thread_id, instance):
- ent = bytes_if_py2('%x-%x-%x-%x' % (
+ ent = bytes_if_py2('{:x}-{:x}-{:x}-{:x}'.format(
node_id, process_id, thread_id, id(instance)))
try:
ret = str(uuid3(NAMESPACE_OID, ent))
@@ -96,10 +95,10 @@ class Broadcast(Queue):
alias=None,
**kwargs):
if unique:
- queue = '{0}.{1}'.format(queue or 'bcast', uuid())
+ queue = '{}.{}'.format(queue or 'bcast', uuid())
else:
- queue = queue or 'bcast.{0}'.format(uuid())
- super(Broadcast, self).__init__(
+ queue = queue or f'bcast.{uuid()}'
+ super().__init__(
alias=alias or name,
queue=queue,
name=queue,
@@ -132,7 +131,7 @@ def _ensure_channel_is_bound(entity, channel):
if not is_bound:
if not channel:
raise ChannelError(
- "Cannot bind channel {} to entity {}".format(channel, entity))
+ f"Cannot bind channel {channel} to entity {entity}")
entity = entity.bind(channel)
return entity
@@ -146,7 +145,7 @@ def _maybe_declare(entity, channel):
if channel is None:
if not entity.is_bound:
raise ChannelError(
- "channel is None and entity {} not bound.".format(entity))
+ f"channel is None and entity {entity} not bound.")
channel = entity.channel
declared = ident = None
@@ -353,7 +352,7 @@ def insured(pool, fun, args, kwargs, errback=None, on_revive=None, **opts):
return retval
-class QoS(object):
+class QoS:
"""Thread safe increment/decrement of a channels prefetch_count.
Arguments:
diff --git a/kombu/compat.py b/kombu/compat.py
index f536220e..2e36da80 100644
--- a/kombu/compat.py
+++ b/kombu/compat.py
@@ -2,7 +2,6 @@
See https://pypi.org/project/carrot/ for documentation.
"""
-from __future__ import absolute_import, unicode_literals
from itertools import count
@@ -55,13 +54,13 @@ class Publisher(messaging.Producer):
routing_key=self.routing_key,
auto_delete=self.auto_delete,
durable=self.durable)
- super(Publisher, self).__init__(connection, self.exchange, **kwargs)
+ super().__init__(connection, self.exchange, **kwargs)
def send(self, *args, **kwargs):
return self.publish(*args, **kwargs)
def close(self):
- super(Publisher, self).close()
+ super().close()
self._closed = True
def __enter__(self):
@@ -115,11 +114,11 @@ class Consumer(messaging.Consumer):
durable=self.durable,
exclusive=self.exclusive,
auto_delete=self.auto_delete)
- super(Consumer, self).__init__(self.backend, queue, **kwargs)
+ super().__init__(self.backend, queue, **kwargs)
def revive(self, channel):
self.backend = channel
- super(Consumer, self).revive(channel)
+ super().revive(channel)
def close(self):
self.cancel()
@@ -188,7 +187,7 @@ class ConsumerSet(messaging.Consumer):
for queue_name, queue_options in items(from_dict):
queues.append(Queue.from_dict(queue_name, **queue_options))
- super(ConsumerSet, self).__init__(self.backend, queues, **kwargs)
+ super().__init__(self.backend, queues, **kwargs)
def iterconsume(self, limit=None, no_ack=False):
return _iterconsume(self.connection, self, no_ack, limit)
@@ -205,7 +204,7 @@ class ConsumerSet(messaging.Consumer):
def revive(self, channel):
self.backend = channel
- super(ConsumerSet, self).revive(channel)
+ super().revive(channel)
def close(self):
self.cancel()
diff --git a/kombu/compression.py b/kombu/compression.py
index 48dca347..b5242672 100644
--- a/kombu/compression.py
+++ b/kombu/compression.py
@@ -1,5 +1,4 @@
"""Compression utilities."""
-from __future__ import absolute_import, unicode_literals
from kombu.utils.encoding import ensure_bytes
diff --git a/kombu/connection.py b/kombu/connection.py
index d8883586..fd3e4c35 100644
--- a/kombu/connection.py
+++ b/kombu/connection.py
@@ -1,5 +1,4 @@
"""Client (Connection)."""
-from __future__ import absolute_import, unicode_literals
import os
import socket
@@ -54,7 +53,7 @@ _log_channel = os.environ.get('KOMBU_LOG_CHANNEL', False)
@python_2_unicode_compatible
-class Connection(object):
+class Connection:
"""A connection to the broker.
Example:
@@ -564,7 +563,7 @@ class Connection(object):
self._debug('ensure channel error: %r',
exc, exc_info=1)
errback and errback(exc, 0)
- _ensured.__name__ = bytes_if_py2('{0}(ensured)'.format(fun.__name__))
+ _ensured.__name__ = bytes_if_py2(f'{fun.__name__}(ensured)')
_ensured.__doc__ = fun.__doc__
_ensured.__module__ = fun.__module__
return _ensured
@@ -592,7 +591,7 @@ class Connection(object):
"""
channels = [channel]
- class Revival(object):
+ class Revival:
__name__ = getattr(fun, '__name__', None)
__module__ = getattr(fun, '__module__', None)
__doc__ = getattr(fun, '__doc__', None)
@@ -637,7 +636,7 @@ class Connection(object):
hostname = self.hostname or D.get('hostname')
if self.uri_prefix:
- hostname = '%s+%s' % (self.uri_prefix, hostname)
+ hostname = f'{self.uri_prefix}+{hostname}'
info = (
('hostname', hostname),
@@ -675,12 +674,12 @@ class Connection(object):
if self.transport.can_parse_url:
connection_as_uri = self.hostname
if self.uri_prefix:
- connection_as_uri = '%s+%s' % (self.uri_prefix, hostname)
+ connection_as_uri = f'{self.uri_prefix}+{hostname}'
if not include_password:
connection_as_uri = maybe_sanitize_url(connection_as_uri)
return connection_as_uri
if self.uri_prefix:
- connection_as_uri = '%s+%s' % (self.uri_prefix, hostname)
+ connection_as_uri = f'{self.uri_prefix}+{hostname}'
if not include_password:
connection_as_uri = maybe_sanitize_url(connection_as_uri)
return connection_as_uri
@@ -814,7 +813,7 @@ class Connection(object):
return exchange_type in self.transport.implements.exchange_type
def __repr__(self):
- return '<Connection: {0} at {1:#x}>'.format(self.as_uri(), id(self))
+ return '<Connection: {} at {:#x}>'.format(self.as_uri(), id(self))
def __copy__(self):
return self.clone()
@@ -976,7 +975,7 @@ class ConnectionPool(Resource):
def __init__(self, connection, limit=None, **kwargs):
self.connection = connection
- super(ConnectionPool, self).__init__(limit=limit)
+ super().__init__(limit=limit)
def new(self):
return self.connection.clone()
@@ -1019,7 +1018,7 @@ class ChannelPool(Resource):
def __init__(self, connection, limit=None, **kwargs):
self.connection = connection
- super(ChannelPool, self).__init__(limit=limit)
+ super().__init__(limit=limit)
def new(self):
return lazy(self.connection.channel)
diff --git a/kombu/entity.py b/kombu/entity.py
index 36976218..2590da71 100644
--- a/kombu/entity.py
+++ b/kombu/entity.py
@@ -1,5 +1,4 @@
"""Exchange and Queue declarations."""
-from __future__ import absolute_import, unicode_literals
import numbers
@@ -26,7 +25,7 @@ def _reprstr(s):
def pretty_bindings(bindings):
- return '[{0}]'.format(', '.join(map(str, bindings)))
+ return '[{}]'.format(', '.join(map(str, bindings)))
def maybe_delivery_mode(
@@ -155,13 +154,13 @@ class Exchange(MaybeChannelBound):
)
def __init__(self, name='', type='', channel=None, **kwargs):
- super(Exchange, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.name = name or self.name
self.type = type or self.type
self.maybe_bind(channel)
def __hash__(self):
- return hash('E|%s' % (self.name,))
+ return hash(f'E|{self.name}')
def _can_declare(self):
return not self.no_declare and (
@@ -310,7 +309,7 @@ class Exchange(MaybeChannelBound):
return self._repr_entity(self)
def __str__(self):
- return 'Exchange {0}({1})'.format(
+ return 'Exchange {}({})'.format(
_reprstr(self.name) or repr(''), self.type,
)
@@ -366,10 +365,10 @@ class binding(Object):
channel=channel)
def __repr__(self):
- return '<binding: {0}>'.format(self)
+ return f'<binding: {self}>'
def __str__(self):
- return '{0}->{1}'.format(
+ return '{}->{}'.format(
_reprstr(self.exchange.name), _reprstr(self.routing_key),
)
@@ -569,7 +568,7 @@ class Queue(MaybeChannelBound):
def __init__(self, name='', exchange=None, routing_key='',
channel=None, bindings=None, on_declared=None,
**kwargs):
- super(Queue, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.name = name or self.name
if isinstance(exchange, str):
self.exchange = Exchange(exchange)
@@ -592,12 +591,12 @@ class Queue(MaybeChannelBound):
def bind(self, channel):
on_declared = self.on_declared
- bound = super(Queue, self).bind(channel)
+ bound = super().bind(channel)
bound.on_declared = on_declared
return bound
def __hash__(self):
- return hash('Q|%s' % (self.name,))
+ return hash(f'Q|{self.name}')
def when_bound(self):
if self.exchange:
@@ -862,7 +861,7 @@ class Queue(MaybeChannelBound):
bindings=bindings)
def as_dict(self, recurse=False):
- res = super(Queue, self).as_dict(recurse)
+ res = super().as_dict(recurse)
if not recurse:
return res
bindings = res.get('bindings')
diff --git a/kombu/exceptions.py b/kombu/exceptions.py
index 2bf802ec..c404a4e9 100644
--- a/kombu/exceptions.py
+++ b/kombu/exceptions.py
@@ -1,5 +1,4 @@
"""Exceptions."""
-from __future__ import absolute_import, unicode_literals
from socket import timeout as TimeoutError # noqa
@@ -85,7 +84,7 @@ class HttpError(Exception):
self.code = code
self.message = message
self.response = response
- super(HttpError, self).__init__(code, message, response)
+ super().__init__(code, message, response)
def __str__(self):
return 'HTTP {0.code}: {0.message}'.format(self)
diff --git a/kombu/five.py b/kombu/five.py
index 1005fef2..19ea7e66 100644
--- a/kombu/five.py
+++ b/kombu/five.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Python 2/3 Compatibility."""
-from __future__ import absolute_import, unicode_literals
import sys
import vine.five
diff --git a/kombu/log.py b/kombu/log.py
index c1df9713..db7573f1 100644
--- a/kombu/log.py
+++ b/kombu/log.py
@@ -1,5 +1,4 @@
"""Logging Utilities."""
-from __future__ import absolute_import, unicode_literals
import logging
import numbers
@@ -54,7 +53,7 @@ def safeify_format(fmt, args, filters=None):
yield filt(args[index]) if filt else args[index]
-class LogMixin(object):
+class LogMixin:
"""Mixin that adds severity methods to any class."""
def debug(self, *args, **kwargs):
@@ -75,7 +74,7 @@ class LogMixin(object):
return self.log(logging.CRITICAL, *args, **kwargs)
def annotate(self, text):
- return '%s - %s' % (self.logger_name, text)
+ return f'{self.logger_name} - {text}'
def log(self, severity, *args, **kwargs):
if DISABLE_TRACEBACKS:
diff --git a/kombu/matcher.py b/kombu/matcher.py
index 018a0955..471e7e35 100644
--- a/kombu/matcher.py
+++ b/kombu/matcher.py
@@ -1,5 +1,4 @@
"""Pattern matching registry."""
-from __future__ import absolute_import, unicode_literals
from re import match as rematch
from fnmatch import fnmatch
@@ -14,7 +13,7 @@ class MatcherNotInstalled(Exception):
pass
-class MatcherRegistry(object):
+class MatcherRegistry:
"""Pattern matching function registry."""
MatcherNotInstalled = MatcherNotInstalled
@@ -34,7 +33,7 @@ class MatcherRegistry(object):
self._matchers.pop(name)
except KeyError:
raise self.MatcherNotInstalled(
- 'No matcher installed for {}'.format(name)
+ f'No matcher installed for {name}'
)
def _set_default_matcher(self, name):
@@ -51,14 +50,14 @@ class MatcherRegistry(object):
self._default_matcher = self._matchers[name]
except KeyError:
raise self.MatcherNotInstalled(
- 'No matcher installed for {}'.format(name)
+ f'No matcher installed for {name}'
)
def match(self, data, pattern, matcher=None, matcher_kwargs=None):
"""Call the matcher."""
if matcher and not self._matchers.get(matcher):
raise self.MatcherNotInstalled(
- 'No matcher installed for {}'.format(matcher)
+ f'No matcher installed for {matcher}'
)
match_func = self._matchers[matcher or 'glob']
if matcher in self.matcher_pattern_first:
diff --git a/kombu/message.py b/kombu/message.py
index aa58a007..c399f503 100644
--- a/kombu/message.py
+++ b/kombu/message.py
@@ -1,5 +1,4 @@
"""Message class."""
-from __future__ import absolute_import, unicode_literals
import sys
@@ -16,7 +15,7 @@ IS_PYPY = hasattr(sys, 'pypy_version_info')
@python_2_unicode_compatible
-class Message(object):
+class Message:
"""Base class for received messages.
Keyword Arguments:
@@ -208,7 +207,7 @@ class Message(object):
return self._decoded_cache if self._decoded_cache else self.decode()
def __repr__(self):
- return '<{0} object at {1:#x} with details {2!r}>'.format(
+ return '<{} object at {:#x} with details {!r}>'.format(
type(self).__name__, id(self), dictfilter(
state=self._state,
content_type=self.content_type,
diff --git a/kombu/messaging.py b/kombu/messaging.py
index 1dc81e6e..7741766b 100644
--- a/kombu/messaging.py
+++ b/kombu/messaging.py
@@ -1,5 +1,4 @@
"""Sending and receiving messages."""
-from __future__ import absolute_import, unicode_literals
from itertools import count
@@ -16,7 +15,7 @@ __all__ = ('Exchange', 'Queue', 'Producer', 'Consumer')
@python_2_unicode_compatible
-class Producer(object):
+class Producer:
"""Message Producer.
Arguments:
@@ -77,7 +76,7 @@ class Producer(object):
self.revive(self._channel)
def __repr__(self):
- return '<Producer: {0._channel}>'.format(self)
+ return f'<Producer: {self._channel}>'
def __reduce__(self):
return self.__class__, self.__reduce_args__()
@@ -277,7 +276,7 @@ class Producer(object):
@python_2_unicode_compatible
-class Consumer(object):
+class Consumer:
"""Message consumer.
Arguments:
@@ -599,7 +598,7 @@ class Consumer(object):
return tag
def _add_tag(self, queue, consumer_tag=None):
- tag = consumer_tag or '{0}{1}'.format(
+ tag = consumer_tag or '{}{}'.format(
self.tag_prefix, next(self._tags))
self._active_tags[queue.name] = tag
return tag
diff --git a/kombu/mixins.py b/kombu/mixins.py
index 75727130..7c6ff917 100644
--- a/kombu/mixins.py
+++ b/kombu/mixins.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""Mixins."""
-from __future__ import absolute_import, unicode_literals
import socket
@@ -37,7 +35,7 @@ Broker connection error, trying again in %s seconds: %r.\
"""
-class ConsumerMixin(object):
+class ConsumerMixin:
"""Convenience mixin for implementing consumer programs.
It can be used outside of threads, with threads, or greenthreads
@@ -200,7 +198,7 @@ class ConsumerMixin(object):
elapsed += safety_interval
if timeout and elapsed >= timeout:
raise
- except socket.error:
+ except OSError:
if not self.should_stop:
raise
else:
diff --git a/kombu/pidbox.py b/kombu/pidbox.py
index 394ad2f1..25b43028 100644
--- a/kombu/pidbox.py
+++ b/kombu/pidbox.py
@@ -1,5 +1,4 @@
"""Generic process mailbox."""
-from __future__ import absolute_import, unicode_literals
import socket
import warnings
@@ -37,7 +36,7 @@ logger = get_logger(__name__)
debug, error = logger.debug, logger.error
-class Node(object):
+class Node:
"""Mailbox node."""
#: hostname of the node.
@@ -151,7 +150,7 @@ class Node(object):
serializer=self.mailbox.serializer)
-class Mailbox(object):
+class Mailbox:
"""Process Mailbox."""
node_cls = Node
@@ -236,7 +235,7 @@ class Mailbox(object):
def get_reply_queue(self):
oid = self.oid
return Queue(
- '%s.%s' % (oid, self.reply_exchange.name),
+ f'{oid}.{self.reply_exchange.name}',
exchange=self.reply_exchange,
routing_key=oid,
durable=False,
@@ -251,7 +250,7 @@ class Mailbox(object):
def get_queue(self, hostname):
return Queue(
- '%s.%s.pidbox' % (hostname, self.namespace),
+ f'{hostname}.{self.namespace}.pidbox',
exchange=self.exchange,
durable=False,
auto_delete=True,
@@ -319,7 +318,7 @@ class Mailbox(object):
if destination is not None and \
not isinstance(destination, (list, tuple)):
raise ValueError(
- 'destination must be a list/tuple not {0}'.format(
+ 'destination must be a list/tuple not {}'.format(
type(destination)))
if (pattern is not None and not isinstance(pattern, string_t) and
matcher is not None and not isinstance(matcher, string_t)):
diff --git a/kombu/pools.py b/kombu/pools.py
index 1a25b1fa..827cb8a7 100644
--- a/kombu/pools.py
+++ b/kombu/pools.py
@@ -1,5 +1,4 @@
"""Public resource pools."""
-from __future__ import absolute_import, unicode_literals
import os
@@ -33,7 +32,7 @@ class ProducerPool(Resource):
def __init__(self, connections, *args, **kwargs):
self.connections = connections
self.Producer = kwargs.pop('Producer', None) or self.Producer
- super(ProducerPool, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
def _acquire_connection(self):
return self.connections.acquire(block=True)
@@ -73,7 +72,7 @@ class ProducerPool(Resource):
if resource.__connection__:
resource.__connection__.release()
resource.channel = None
- super(ProducerPool, self).release(resource)
+ super().release(resource)
class PoolGroup(EqualityDict):
diff --git a/kombu/resource.py b/kombu/resource.py
index b9715d4a..7fd54797 100644
--- a/kombu/resource.py
+++ b/kombu/resource.py
@@ -1,5 +1,4 @@
"""Generic resource pool implementation."""
-from __future__ import absolute_import, unicode_literals
import os
@@ -25,7 +24,7 @@ class LifoQueue(_LifoQueue):
self.queue = deque()
-class Resource(object):
+class Resource:
"""Pool of resources."""
LimitExceeded = exceptions.LimitExceeded
@@ -174,7 +173,7 @@ class Resource(object):
if (self._dirty and 0 < limit < self._limit) and not ignore_errors:
if not force:
raise RuntimeError(
- "Can't shrink pool when in use: was={0} now={1}".format(
+ "Can't shrink pool when in use: was={} now={}".format(
self._limit, limit))
reset = True
self._limit = limit
@@ -220,10 +219,10 @@ class Resource(object):
def acquire(self, *args, **kwargs): # noqa
import traceback
id = self._next_resource_id = self._next_resource_id + 1
- print('+{0} ACQUIRE {1}'.format(id, self.__class__.__name__))
+ print(f'+{id} ACQUIRE {self.__class__.__name__}')
r = self._orig_acquire(*args, **kwargs)
r._resource_id = id
- print('-{0} ACQUIRE {1}'.format(id, self.__class__.__name__))
+ print(f'-{id} ACQUIRE {self.__class__.__name__}')
if not hasattr(r, 'acquired_by'):
r.acquired_by = []
r.acquired_by.append(traceback.format_stack())
@@ -231,8 +230,8 @@ class Resource(object):
def release(self, resource): # noqa
id = resource._resource_id
- print('+{0} RELEASE {1}'.format(id, self.__class__.__name__))
+ print(f'+{id} RELEASE {self.__class__.__name__}')
r = self._orig_release(resource)
- print('-{0} RELEASE {1}'.format(id, self.__class__.__name__))
+ print(f'-{id} RELEASE {self.__class__.__name__}')
self._next_resource_id -= 1
return r
diff --git a/kombu/serialization.py b/kombu/serialization.py
index 8469a89f..ee833839 100644
--- a/kombu/serialization.py
+++ b/kombu/serialization.py
@@ -1,5 +1,4 @@
"""Serialization utilities."""
-from __future__ import absolute_import, unicode_literals
import codecs
import os
@@ -60,10 +59,10 @@ def pickle_loads(s, load=pickle_load):
def parenthesize_alias(first, second):
- return '%s (%s)' % (first, second) if first else second
+ return f'{first} ({second})' if first else second
-class SerializerRegistry(object):
+class SerializerRegistry:
"""The registry keeps track of serialization methods."""
def __init__(self):
@@ -137,7 +136,7 @@ class SerializerRegistry(object):
self.name_to_type.pop(name, None)
except KeyError:
raise SerializerNotInstalled(
- 'No encoder/decoder installed for {0}'.format(name))
+ f'No encoder/decoder installed for {name}')
def _set_default_serializer(self, name):
"""Set the default serialization method used by this library.
@@ -156,7 +155,7 @@ class SerializerRegistry(object):
self._default_encode) = self._encoders[name]
except KeyError:
raise SerializerNotInstalled(
- 'No encoder installed for {0}'.format(name))
+ f'No encoder installed for {name}')
def dumps(self, data, serializer=None):
"""Encode data.
@@ -193,7 +192,7 @@ class SerializerRegistry(object):
return raw_encode(data)
if serializer and not self._encoders.get(serializer):
raise SerializerNotInstalled(
- 'No encoder installed for {0}'.format(serializer))
+ f'No encoder installed for {serializer}')
# If a raw string was sent, assume binary encoding
# (it's likely either ASCII or a raw binary file, and a character
@@ -269,7 +268,7 @@ class SerializerRegistry(object):
def _for_untrusted_content(self, ctype, why):
return ContentDisallowed(
- 'Refusing to deserialize {0} content of type {1}'.format(
+ 'Refusing to deserialize {} content of type {}'.format(
why,
parenthesize_alias(self.type_to_name.get(ctype, ctype), ctype),
),
diff --git a/kombu/simple.py b/kombu/simple.py
index b8d079a0..a02f32d6 100644
--- a/kombu/simple.py
+++ b/kombu/simple.py
@@ -1,5 +1,4 @@
"""Simple messaging interface."""
-from __future__ import absolute_import, unicode_literals
import socket
@@ -13,7 +12,7 @@ from .five import Empty, monotonic
__all__ = ('SimpleQueue', 'SimpleBuffer')
-class SimpleBase(object):
+class SimpleBase:
Empty = Empty
_consuming = False
@@ -139,7 +138,7 @@ class SimpleQueue(SimpleBase):
serializer=serializer,
routing_key=routing_key,
compression=compression)
- super(SimpleQueue, self).__init__(channel, producer,
+ super().__init__(channel, producer,
consumer, no_ack, **kwargs)
diff --git a/kombu/transport/SLMQ.py b/kombu/transport/SLMQ.py
index 5848f720..cb88c4d9 100644
--- a/kombu/transport/SLMQ.py
+++ b/kombu/transport/SLMQ.py
@@ -1,5 +1,4 @@
"""SoftLayer Message Queue transport."""
-from __future__ import absolute_import, unicode_literals
import socket
import string
@@ -39,7 +38,7 @@ class Channel(virtual.Channel):
raise ImportError(
'SLMQ transport requires the softlayer_messaging library',
)
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
queues = self.slmq.queues()
for queue in queues:
self._queue_cache[queue] = queue
@@ -47,14 +46,14 @@ class Channel(virtual.Channel):
def basic_consume(self, queue, no_ack, *args, **kwargs):
if no_ack:
self._noack_queues.add(queue)
- return super(Channel, self).basic_consume(queue, no_ack,
+ return super().basic_consume(queue, no_ack,
*args, **kwargs)
def basic_cancel(self, consumer_tag):
if consumer_tag in self._consumers:
queue = self._tag_to_queue[consumer_tag]
self._noack_queues.discard(queue)
- return super(Channel, self).basic_cancel(consumer_tag)
+ return super().basic_cancel(consumer_tag)
def entity_name(self, name, table=CHARS_REPLACE_TABLE):
"""Format AMQP queue name into a valid SLQS queue name."""
@@ -79,7 +78,7 @@ class Channel(virtual.Channel):
queue_name = self.entity_name(queue)
self._queue_cache.pop(queue_name, None)
self.slmq.queue(queue_name).delete(force=True)
- super(Channel, self)._delete(queue_name)
+ super()._delete(queue_name)
def _put(self, queue, message, **kwargs):
"""Put message onto queue."""
@@ -109,7 +108,7 @@ class Channel(virtual.Channel):
pass
else:
self.delete_message(queue, delivery_info['slmq_message_id'])
- super(Channel, self).basic_ack(delivery_tag)
+ super().basic_ack(delivery_tag)
def _size(self, queue):
"""Return the number of messages in a queue."""
@@ -143,9 +142,9 @@ class Channel(virtual.Channel):
secure = bool(os.environ.get(
'SLMQ_SECURE', self.transport_options.get('secure')) or True,
)
- endpoint = '{0}://{1}{2}'.format(
+ endpoint = '{}://{}{}'.format(
'https' if secure else 'http', host,
- ':{0}'.format(port) if port else '',
+ f':{port}' if port else '',
)
self._slmq = get_client(account, endpoint=endpoint)
diff --git a/kombu/transport/SQS.py b/kombu/transport/SQS.py
index 768b93d0..d5c00453 100644
--- a/kombu/transport/SQS.py
+++ b/kombu/transport/SQS.py
@@ -73,7 +73,6 @@ Other Features supported by this transport:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
""" # noqa: E501
-from __future__ import absolute_import, unicode_literals
import base64
import socket
@@ -139,7 +138,7 @@ class Channel(virtual.Channel):
def __init__(self, *args, **kwargs):
if boto3 is None:
raise ImportError('boto3 is not installed')
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
# SQS blows up if you try to create a new queue when one already
# exists but with a different visibility_timeout. This prepopulates
@@ -165,7 +164,7 @@ class Channel(virtual.Channel):
self._noack_queues.add(queue)
if self.hub:
self._loop1(queue)
- return super(Channel, self).basic_consume(
+ return super().basic_consume(
queue, no_ack, *args, **kwargs
)
@@ -173,7 +172,7 @@ class Channel(virtual.Channel):
if consumer_tag in self._consumers:
queue = self._tag_to_queue[consumer_tag]
self._noack_queues.discard(queue)
- return super(Channel, self).basic_cancel(consumer_tag)
+ return super().basic_cancel(consumer_tag)
def drain_events(self, timeout=None, callback=None, **kwargs):
"""Return a single payload message from one of our queues.
@@ -264,7 +263,7 @@ class Channel(virtual.Channel):
"""Delete queue by name."""
if self.predefined_queues:
return
- super(Channel, self)._delete(queue)
+ super()._delete(queue)
self._queue_cache.pop(queue, None)
def _put(self, queue, message, **kwargs):
@@ -466,14 +465,14 @@ class Channel(virtual.Channel):
for unwanted_key in unwanted_delivery_info:
# Remove objects that aren't JSON serializable (Issue #1108).
message.delivery_info.pop(unwanted_key, None)
- return super(Channel, self)._restore(message)
+ return super()._restore(message)
def basic_ack(self, delivery_tag, multiple=False):
try:
message = self.qos.get(delivery_tag).delivery_info
sqs_message = message['sqs_message']
except KeyError:
- super(Channel, self).basic_ack(delivery_tag)
+ super().basic_ack(delivery_tag)
else:
queue = None
if 'routing_key' in message:
@@ -485,9 +484,9 @@ class Channel(virtual.Channel):
ReceiptHandle=sqs_message['ReceiptHandle']
)
except ClientError:
- super(Channel, self).basic_reject(delivery_tag)
+ super().basic_reject(delivery_tag)
else:
- super(Channel, self).basic_ack(delivery_tag)
+ super().basic_ack(delivery_tag)
def _size(self, queue):
"""Return the number of messages in a queue."""
@@ -512,7 +511,7 @@ class Channel(virtual.Channel):
return size
def close(self):
- super(Channel, self).close()
+ super().close()
# if self._asynsqs:
# try:
# self.asynsqs().close()
@@ -637,7 +636,7 @@ class Channel(virtual.Channel):
if self.conninfo.hostname is not None:
scheme = 'https' if self.is_secure else 'http'
if self.conninfo.port is not None:
- port = ':{}'.format(self.conninfo.port)
+ port = f':{self.conninfo.port}'
else:
port = ''
return '{}://{}{}'.format(
diff --git a/kombu/transport/__init__.py b/kombu/transport/__init__.py
index cd2a3b3e..0a9a4454 100644
--- a/kombu/transport/__init__.py
+++ b/kombu/transport/__init__.py
@@ -1,5 +1,4 @@
"""Built-in transports."""
-from __future__ import absolute_import, unicode_literals
from kombu.five import string_t
from kombu.utils.compat import _detect_environment
@@ -63,9 +62,9 @@ def resolve_transport(transport=None):
alt = fmatch_best(transport, TRANSPORT_ALIASES)
if alt:
raise KeyError(
- 'No such transport: {0}. Did you mean {1}?'.format(
+ 'No such transport: {}. Did you mean {}?'.format(
transport, alt))
- raise KeyError('No such transport: {0}'.format(transport))
+ raise KeyError(f'No such transport: {transport}')
else:
if callable(transport):
transport = transport()
diff --git a/kombu/transport/azureservicebus.py b/kombu/transport/azureservicebus.py
index c96350af..e1c6b4fa 100644
--- a/kombu/transport/azureservicebus.py
+++ b/kombu/transport/azureservicebus.py
@@ -17,7 +17,6 @@ More information about Azure Service Bus:
https://azure.microsoft.com/en-us/services/service-bus/
"""
-from __future__ import absolute_import, unicode_literals
import string
@@ -60,7 +59,7 @@ class Channel(virtual.Channel):
raise ImportError('Azure Service Bus transport requires the '
'azure-servicebus library')
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
for queue in self.queue_service.list_queues():
self._queue_cache[queue] = queue
@@ -84,7 +83,7 @@ class Channel(virtual.Channel):
queue_name = self.entity_name(queue)
self._queue_cache.pop(queue_name, None)
self.queue_service.delete_queue(queue_name)
- super(Channel, self)._delete(queue_name)
+ super()._delete(queue_name)
def _put(self, queue, message, **kwargs):
"""Put message onto queue."""
diff --git a/kombu/transport/azurestoragequeues.py b/kombu/transport/azurestoragequeues.py
index f7918688..78f8acde 100644
--- a/kombu/transport/azurestoragequeues.py
+++ b/kombu/transport/azurestoragequeues.py
@@ -13,7 +13,6 @@ More information about Azure Storage Queues:
https://azure.microsoft.com/en-us/services/storage/queues/
"""
-from __future__ import absolute_import, unicode_literals
import string
@@ -50,7 +49,7 @@ class Channel(virtual.Channel):
raise ImportError('Azure Storage Queues transport requires the '
'azure-storage-queue library')
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
for queue_name in self.queue_service.list_queues():
self._queue_name_cache[queue_name] = queue_name
@@ -59,7 +58,7 @@ class Channel(virtual.Channel):
if no_ack:
self._noack_queues.add(queue)
- return super(Channel, self).basic_consume(queue, no_ack,
+ return super().basic_consume(queue, no_ack,
*args, **kwargs)
def entity_name(self, name, table=CHARS_REPLACE_TABLE):
@@ -81,7 +80,7 @@ class Channel(virtual.Channel):
queue_name = self.entity_name(queue)
self._queue_name_cache.pop(queue_name, None)
self.queue_service.delete_queue(queue_name)
- super(Channel, self)._delete(queue_name)
+ super()._delete(queue_name)
def _put(self, queue, message, **kwargs):
"""Put message onto queue."""
diff --git a/kombu/transport/base.py b/kombu/transport/base.py
index 3f2dfece..5d38206a 100644
--- a/kombu/transport/base.py
+++ b/kombu/transport/base.py
@@ -1,7 +1,6 @@
"""Base transport interface."""
# flake8: noqa
-from __future__ import absolute_import, unicode_literals
import errno
import socket
@@ -72,7 +71,7 @@ def _LeftBlank(obj, method):
obj.__class__, method))
-class StdChannel(object):
+class StdChannel:
"""Standard channel base class."""
no_ack_consumers = None
@@ -107,7 +106,7 @@ class StdChannel(object):
self.close()
-class Management(object):
+class Management:
"""AMQP Management API (incomplete)."""
def __init__(self, transport):
@@ -140,7 +139,7 @@ default_transport_capabilities = Implements(
)
-class Transport(object):
+class Transport:
"""Base class for transports."""
Management = Management
diff --git a/kombu/transport/consul.py b/kombu/transport/consul.py
index 26dca7ac..980487ba 100644
--- a/kombu/transport/consul.py
+++ b/kombu/transport/consul.py
@@ -4,7 +4,6 @@ It uses Consul.io's Key/Value store to transport messages in Queues
It uses python-consul for talking to Consul's HTTP API
"""
-from __future__ import absolute_import, unicode_literals
import uuid
import socket
@@ -47,7 +46,7 @@ class Channel(virtual.Channel):
if consul is None:
raise ImportError('Missing python-consul library')
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
port = self.connection.client.port or self.connection.default_port
host = self.connection.client.hostname or DEFAULT_HOST
@@ -59,10 +58,10 @@ class Channel(virtual.Channel):
self.client = consul.Consul(host=host, port=int(port))
def _lock_key(self, queue):
- return '{0}/{1}.lock'.format(self.prefix, queue)
+ return f'{self.prefix}/{queue}.lock'
def _key_prefix(self, queue):
- return '{0}/{1}'.format(self.prefix, queue)
+ return f'{self.prefix}/{queue}'
def _get_or_create_session(self, queue):
"""Get or create consul session.
@@ -178,13 +177,13 @@ class Channel(virtual.Channel):
This simply writes a key to the K/V store of Consul
"""
- key = '{0}/msg/{1}_{2}'.format(
+ key = '{}/msg/{}_{}'.format(
self._key_prefix(queue),
int(round(monotonic() * 1000)),
uuid.uuid4(),
)
if not self.client.kv.put(key=key, value=dumps(payload), cas=0):
- raise ChannelError('Cannot add key {0!r} to consul'.format(key))
+ raise ChannelError(f'Cannot add key {key!r} to consul')
def _get(self, queue, timeout=None):
"""Get the first available message from the queue.
@@ -193,7 +192,7 @@ class Channel(virtual.Channel):
only one node reads at the same time. This is for read consistency
"""
with self._queue_lock(queue, raising=Empty):
- key = '{0}/msg/'.format(self._key_prefix(queue))
+ key = '{}/msg/'.format(self._key_prefix(queue))
logger.debug('Fetching key %s with index %s', key, self.index)
self.index, data = self.client.kv.get(
key=key, recurse=True,
@@ -219,14 +218,14 @@ class Channel(virtual.Channel):
def _purge(self, queue):
self._destroy_session(queue)
return self.client.kv.delete(
- key='{0}/msg/'.format(self._key_prefix(queue)),
+ key='{}/msg/'.format(self._key_prefix(queue)),
recurse=True,
)
def _size(self, queue):
size = 0
try:
- key = '{0}/msg/'.format(self._key_prefix(queue))
+ key = '{}/msg/'.format(self._key_prefix(queue))
logger.debug('Fetching key recursively %s with index %s',
key, self.index)
self.index, data = self.client.kv.get(
@@ -243,7 +242,7 @@ class Channel(virtual.Channel):
@cached_property
def lock_name(self):
- return '{0}'.format(socket.gethostname())
+ return f'{socket.gethostname()}'
class Transport(virtual.Transport):
@@ -259,7 +258,7 @@ class Transport(virtual.Transport):
if consul is None:
raise ImportError('Missing python-consul library')
- super(Transport, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self.connection_errors = (
virtual.Transport.connection_errors + (
diff --git a/kombu/transport/etcd.py b/kombu/transport/etcd.py
index 04e67cda..99a910c0 100644
--- a/kombu/transport/etcd.py
+++ b/kombu/transport/etcd.py
@@ -4,7 +4,6 @@ It uses Etcd as a store to transport messages in Queues
It uses python-etcd for talking to Etcd's HTTP API
"""
-from __future__ import absolute_import, unicode_literals
import os
import socket
@@ -44,7 +43,7 @@ class Channel(virtual.Channel):
if etcd is None:
raise ImportError('Missing python-etcd library')
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
port = self.connection.client.port or self.connection.default_port
host = self.connection.client.hostname or DEFAULT_HOST
@@ -61,7 +60,7 @@ class Channel(virtual.Channel):
Arguments:
queue (str): The name of the queue.
"""
- return '{0}/{1}'.format(self.prefix, queue)
+ return f'{self.prefix}/{queue}'
@contextmanager
def _queue_lock(self, queue):
@@ -78,12 +77,12 @@ class Channel(virtual.Channel):
"""
lock = etcd.Lock(self.client, queue)
lock._uuid = self.lock_value
- logger.debug('Acquiring lock {0}'.format(lock.name))
+ logger.debug(f'Acquiring lock {lock.name}')
lock.acquire(blocking=True, lock_ttl=self.lock_ttl)
try:
yield
finally:
- logger.debug('Releasing lock {0}'.format(lock.name))
+ logger.debug(f'Releasing lock {lock.name}')
lock.release()
def _new_queue(self, queue, **_):
@@ -98,7 +97,7 @@ class Channel(virtual.Channel):
return self.client.write(
key=self._key_prefix(queue), dir=True, value=None)
except etcd.EtcdNotFile:
- logger.debug('Queue "{0}" already exists'.format(queue))
+ logger.debug(f'Queue "{queue}" already exists')
return self.client.read(key=self._key_prefix(queue))
def _has_queue(self, queue, **kwargs):
@@ -138,7 +137,7 @@ class Channel(virtual.Channel):
key=key,
value=dumps(payload),
append=True):
- raise ChannelError('Cannot add key {0!r} to etcd'.format(key))
+ raise ChannelError(f'Cannot add key {key!r} to etcd')
def _get(self, queue, timeout=None):
"""Get the first available message from the queue.
@@ -163,13 +162,13 @@ class Channel(virtual.Channel):
raise Empty()
item = result._children[-1]
- logger.debug('Removing key {0}'.format(item['key']))
+ logger.debug('Removing key {}'.format(item['key']))
msg_content = loads(item['value'])
self.client.delete(key=item['key'])
return msg_content
except (TypeError, IndexError, etcd.EtcdException) as error:
- logger.debug('_get failed: {0}:{1}'.format(type(error), error))
+ logger.debug('_get failed: {}:{}'.format(type(error), error))
raise Empty()
@@ -181,7 +180,7 @@ class Channel(virtual.Channel):
"""
with self._queue_lock(queue):
key = self._key_prefix(queue)
- logger.debug('Purging queue at key {0}'.format(key))
+ logger.debug(f'Purging queue at key {key}')
return self.client.delete(key=key, recursive=True)
def _size(self, queue):
@@ -209,7 +208,7 @@ class Channel(virtual.Channel):
@cached_property
def lock_value(self):
- return '{0}.{1}'.format(socket.gethostname(), os.getpid())
+ return f'{socket.gethostname()}.{os.getpid()}'
class Transport(virtual.Transport):
@@ -230,7 +229,7 @@ class Transport(virtual.Transport):
if etcd is None:
raise ImportError('Missing python-etcd library')
- super(Transport, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self.connection_errors = (
virtual.Transport.connection_errors + (etcd.EtcdException, )
diff --git a/kombu/transport/filesystem.py b/kombu/transport/filesystem.py
index b27dfdb8..ac447026 100644
--- a/kombu/transport/filesystem.py
+++ b/kombu/transport/filesystem.py
@@ -2,7 +2,6 @@
Transport using the file-system as the message store.
"""
-from __future__ import absolute_import, unicode_literals
import os
import shutil
@@ -65,7 +64,7 @@ class Channel(virtual.Channel):
def _put(self, queue, payload, **kwargs):
"""Put `message` onto `queue`."""
- filename = '%s_%s.%s.msg' % (int(round(monotonic() * 1000)),
+ filename = '{}_{}.{}.msg'.format(int(round(monotonic() * 1000)),
uuid.uuid4(), queue)
filename = os.path.join(self.data_folder_out, filename)
@@ -73,9 +72,9 @@ class Channel(virtual.Channel):
f = open(filename, 'wb')
lock(f, LOCK_EX)
f.write(str_to_bytes(dumps(payload)))
- except (IOError, OSError):
+ except OSError:
raise ChannelError(
- 'Cannot add file {0!r} to directory'.format(filename))
+ f'Cannot add file {filename!r} to directory')
finally:
unlock(f)
f.close()
@@ -101,7 +100,7 @@ class Channel(virtual.Channel):
# move the file to the tmp/processed folder
shutil.move(os.path.join(self.data_folder_in, filename),
processed_folder)
- except IOError:
+ except OSError:
pass # file could be locked, or removed in meantime so ignore
filename = os.path.join(processed_folder, filename)
@@ -111,9 +110,9 @@ class Channel(virtual.Channel):
f.close()
if not self.store_processed:
os.remove(filename)
- except (IOError, OSError):
+ except OSError:
raise ChannelError(
- 'Cannot read file {0!r} from queue.'.format(filename))
+ f'Cannot read file {filename!r} from queue.')
return loads(bytes_to_str(payload))
@@ -148,7 +147,7 @@ class Channel(virtual.Channel):
"""Return the number of messages in `queue` as an :class:`int`."""
count = 0
- queue_find = '.{0}.msg'.format(queue)
+ queue_find = f'.{queue}.msg'
folder = os.listdir(self.data_folder_in)
while len(folder) > 0:
filename = folder.pop()
diff --git a/kombu/transport/librabbitmq.py b/kombu/transport/librabbitmq.py
index 4fc9cc99..20a45745 100644
--- a/kombu/transport/librabbitmq.py
+++ b/kombu/transport/librabbitmq.py
@@ -2,7 +2,6 @@
.. _`librabbitmq`: https://pypi.org/project/librabbitmq/
"""
-from __future__ import absolute_import, unicode_literals
import os
import socket
@@ -34,7 +33,7 @@ class Message(base.Message):
"""AMQP Message (librabbitmq)."""
def __init__(self, channel, props, info, body):
- super(Message, self).__init__(
+ super().__init__(
channel=channel,
body=body,
delivery_info=info,
diff --git a/kombu/transport/memory.py b/kombu/transport/memory.py
index cbfd41bf..922d2d47 100644
--- a/kombu/transport/memory.py
+++ b/kombu/transport/memory.py
@@ -1,5 +1,4 @@
"""In-memory transport."""
-from __future__ import absolute_import, unicode_literals
from kombu.five import Queue, values
@@ -54,7 +53,7 @@ class Channel(virtual.Channel):
return size
def close(self):
- super(Channel, self).close()
+ super().close()
for queue in values(self.queues):
queue.empty()
self.queues = {}
diff --git a/kombu/transport/mongodb.py b/kombu/transport/mongodb.py
index 37d90c33..1ebc1d96 100644
--- a/kombu/transport/mongodb.py
+++ b/kombu/transport/mongodb.py
@@ -3,7 +3,6 @@
:copyright: (c) 2010 - 2013 by Flavio Percoco Premoli.
:license: BSD, see LICENSE for more details.
"""
-from __future__ import absolute_import, unicode_literals
import datetime
@@ -32,7 +31,7 @@ Kombu requires MongoDB version 2.2+ (server is {0}) for TTL indexes support\
"""
-class BroadcastCursor(object):
+class BroadcastCursor:
"""Cursor for broadcast queues."""
def __init__(self, cursor):
@@ -112,7 +111,7 @@ class Channel(virtual.Channel):
))
def __init__(self, *vargs, **kwargs):
- super(Channel, self).__init__(*vargs, **kwargs)
+ super().__init__(*vargs, **kwargs)
self._broadcast_cursors = {}
@@ -155,7 +154,7 @@ class Channel(virtual.Channel):
# Do not calculate actual queue size if requested
# for performance considerations
if not self.calc_queue_size:
- return super(Channel, self)._size(queue)
+ return super()._size(queue)
if queue in self._fanout_queues:
return self._get_broadcast_cursor(queue).get_size()
@@ -225,7 +224,7 @@ class Channel(virtual.Channel):
if self.ttl:
self.queues.remove({'_id': queue})
- super(Channel, self).queue_delete(queue, **kwargs)
+ super().queue_delete(queue, **kwargs)
if queue in self._fanout_queues:
try:
diff --git a/kombu/transport/pyamqp.py b/kombu/transport/pyamqp.py
index ef2cdc6d..8bd663f9 100644
--- a/kombu/transport/pyamqp.py
+++ b/kombu/transport/pyamqp.py
@@ -1,5 +1,4 @@
"""Pure-Python amqp transport."""
-from __future__ import absolute_import, unicode_literals
import amqp
@@ -19,7 +18,7 @@ class Message(base.Message):
def __init__(self, msg, channel=None, **kwargs):
props = msg.properties
- super(Message, self).__init__(
+ super().__init__(
body=msg.body,
channel=channel,
delivery_tag=msg.delivery_tag,
@@ -173,7 +172,7 @@ class SSLTransport(Transport):
"""AMQP SSL Transport."""
def __init__(self, *args, **kwargs):
- super(SSLTransport, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
# ugh, not exactly pure, but hey, it's python.
if not self.client.ssl: # not dict or False
diff --git a/kombu/transport/pyro.py b/kombu/transport/pyro.py
index 7e022273..6d5a0a97 100644
--- a/kombu/transport/pyro.py
+++ b/kombu/transport/pyro.py
@@ -11,7 +11,6 @@ This broker can be launched by simply executing this transport module directly,
with the command: ``python -m kombu.transport.pyro``
"""
-from __future__ import absolute_import, unicode_literals
import sys
@@ -42,7 +41,7 @@ class Channel(virtual.Channel):
"""Pyro Channel."""
def close(self):
- super(Channel, self).close()
+ super().close()
if self.shared_queues:
self.shared_queues._pyroRelease()
@@ -129,7 +128,7 @@ if pyro is not None:
@pyro.expose
@pyro.behavior(instance_mode="single")
- class KombuBroker(object):
+ class KombuBroker:
"""Kombu Broker used by the Pyro transport.
You have to run this as a separate (Pyro) service.
@@ -174,11 +173,11 @@ if pyro is not None:
if __name__ == "__main__":
print("Launching Broker for Kombu's Pyro transport.")
with pyro.Daemon() as daemon:
- print("(Expecting a Pyro name server at {0}:{1})"
+ print("(Expecting a Pyro name server at {}:{})"
.format(pyro.config.NS_HOST, pyro.config.NS_PORT))
with pyro.locateNS() as ns:
print("You can connect with Kombu using the url "
- "'pyro://{0}/kombu.broker'".format(pyro.config.NS_HOST))
+ "'pyro://{}/kombu.broker'".format(pyro.config.NS_HOST))
uri = daemon.register(KombuBroker)
ns.register("kombu.broker", uri)
daemon.requestLoop()
diff --git a/kombu/transport/qpid.py b/kombu/transport/qpid.py
index 3eaaf914..97851164 100644
--- a/kombu/transport/qpid.py
+++ b/kombu/transport/qpid.py
@@ -76,7 +76,6 @@ options override and replace any other default or specified values. If using
Celery, this can be accomplished by setting the
*BROKER_TRANSPORT_OPTIONS* Celery option.
"""
-from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
import os
@@ -148,7 +147,7 @@ class AuthenticationFailure(Exception):
"""Cannot authenticate with Qpid."""
-class QoS(object):
+class QoS:
"""A helper object for message prefetch and ACKing purposes.
:keyword prefetch_count: Initial prefetch count, hard set to 1.
@@ -465,11 +464,11 @@ class Channel(base.StdChannel):
"""
if not exchange:
- address = '%s; {assert: always, node: {type: queue}}' % (
- routing_key,)
+ address = '{}; {{assert: always, node: {{type: queue}}}}'.format(
+ routing_key)
msg_subject = None
else:
- address = '%s/%s; {assert: always, node: {type: topic}}' % (
+ address = '{}/{}; {{assert: always, node: {{type: topic}}}}'.format(
exchange, routing_key)
msg_subject = str(routing_key)
sender = self.transport.session.sender(address)
@@ -517,7 +516,7 @@ class Channel(base.StdChannel):
"""
queue_to_purge = self._broker.getQueue(queue)
if queue_to_purge is None:
- error_text = "NOT_FOUND - no queue '{0}'".format(queue)
+ error_text = f"NOT_FOUND - no queue '{queue}'"
raise NotFound(code=404, text=error_text)
message_count = queue_to_purge.values['msgDepth']
if message_count > 0:
@@ -1212,7 +1211,7 @@ class Channel(base.StdChannel):
return default
-class Connection(object):
+class Connection:
"""Qpid Connection.
Encapsulate a connection object for the
@@ -1436,7 +1435,7 @@ class Transport(base.Transport):
def __init__(self, *args, **kwargs):
self.verify_runtime_environment()
- super(Transport, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self.use_async_interface = False
def verify_runtime_environment(self):
diff --git a/kombu/transport/redis.py b/kombu/transport/redis.py
index cf6dd296..d8f39d01 100644
--- a/kombu/transport/redis.py
+++ b/kombu/transport/redis.py
@@ -1,5 +1,4 @@
"""Redis transport."""
-from __future__ import absolute_import, unicode_literals
import numbers
import socket
@@ -138,7 +137,7 @@ class QoS(virtual.QoS):
restore_at_shutdown = True
def __init__(self, *args, **kwargs):
- super(QoS, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
self._vrestore_count = 0
def append(self, message, delivery_tag):
@@ -156,7 +155,7 @@ class QoS(virtual.QoS):
.hset(self.unacked_key, delivery_tag,
dumps([message._raw, EX, RK])) \
.execute()
- super(QoS, self).append(message, delivery_tag)
+ super().append(message, delivery_tag)
def restore_unacked(self, client=None):
with self.channel.conn_or_acquire(client) as client:
@@ -166,7 +165,7 @@ class QoS(virtual.QoS):
def ack(self, delivery_tag):
self._remove_from_indices(delivery_tag).execute()
- super(QoS, self).ack(delivery_tag)
+ super().ack(delivery_tag)
def reject(self, delivery_tag, requeue=False):
if requeue:
@@ -236,7 +235,7 @@ class QoS(virtual.QoS):
return self.channel.visibility_timeout
-class MultiChannelPoller(object):
+class MultiChannelPoller:
"""Async I/O poller for Redis transport."""
eventflags = READ | ERR
@@ -496,7 +495,7 @@ class Channel(virtual.Channel):
connection_class = redis.Connection if redis else None
def __init__(self, *args, **kwargs):
- super(Channel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
if not self.ack_emulation: # disable visibility timeout
self.QoS = virtual.QoS
@@ -572,7 +571,7 @@ class Channel(virtual.Channel):
def _restore(self, message, leftmost=False):
if not self.ack_emulation:
- return super(Channel, self)._restore(message)
+ return super()._restore(message)
tag = message.delivery_tag
with self.conn_or_acquire() as client:
with client.pipeline() as pipe:
@@ -591,7 +590,7 @@ class Channel(virtual.Channel):
exchange, _ = self._fanout_queues[queue]
self.active_fanout_queues.add(queue)
self._fanout_to_queue[exchange] = queue
- ret = super(Channel, self).basic_consume(queue, *args, **kwargs)
+ ret = super().basic_consume(queue, *args, **kwargs)
# Update fair cycle between queues.
#
@@ -635,7 +634,7 @@ class Channel(virtual.Channel):
self._fanout_to_queue.pop(exchange)
except KeyError:
pass
- ret = super(Channel, self).basic_cancel(consumer_tag)
+ ret = super().basic_cancel(consumer_tag)
self._update_queue_cycle()
return ret
@@ -774,7 +773,7 @@ class Channel(virtual.Channel):
def _q_for_pri(self, queue, pri):
pri = self.priority(pri)
if pri:
- return "{}{}{}".format(queue, self.sep, pri)
+ return f"{queue}{self.sep}{pri}"
return queue
def priority(self, n):
@@ -862,7 +861,7 @@ class Channel(virtual.Channel):
self.queue_delete(queue, client=client)
self._disconnect_pools()
self._close_clients()
- super(Channel, self).close()
+ super().close()
def _close_clients(self):
# Close connections
@@ -884,7 +883,7 @@ class Channel(virtual.Channel):
vhost = int(vhost)
except ValueError:
raise ValueError(
- 'Database is int between 0 and limit - 1, not {0}'.format(
+ 'Database is int between 0 and limit - 1, not {}'.format(
vhost,
))
return vhost
@@ -955,7 +954,7 @@ class Channel(virtual.Channel):
if asynchronous:
class Connection(connection_cls):
def disconnect(self):
- super(Connection, self).disconnect()
+ super().disconnect()
channel._on_connection_disconnect(self)
connection_cls = Connection
@@ -1042,7 +1041,7 @@ class Transport(virtual.Transport):
def __init__(self, *args, **kwargs):
if redis is None:
raise ImportError('Missing redis library (pip install redis)')
- super(Transport, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
# Get redis-py exceptions.
self.connection_errors, self.channel_errors = self._get_errors()
diff --git a/kombu/transport/sqlalchemy/__init__.py b/kombu/transport/sqlalchemy/__init__.py
index 08af3054..863659c9 100644
--- a/kombu/transport/sqlalchemy/__init__.py
+++ b/kombu/transport/sqlalchemy/__init__.py
@@ -2,7 +2,6 @@
# SQLAlchemy overrides != False to have special meaning and pep8 complains
# flake8: noqa
-from __future__ import absolute_import, unicode_literals
import threading
from json import loads, dumps
@@ -33,7 +32,7 @@ class Channel(virtual.Channel):
def __init__(self, connection, **kwargs):
self._configure_entity_tablenames(connection.client.transport_options)
- super(Channel, self).__init__(connection, **kwargs)
+ super().__init__(connection, **kwargs)
def _configure_entity_tablenames(self, opts):
self.queue_tablename = opts.get('queue_tablename', 'kombu_queue')
diff --git a/kombu/transport/sqlalchemy/models.py b/kombu/transport/sqlalchemy/models.py
index 78d2645a..eefa529b 100644
--- a/kombu/transport/sqlalchemy/models.py
+++ b/kombu/transport/sqlalchemy/models.py
@@ -1,5 +1,4 @@
"""Kombu transport using SQLAlchemy as the message store."""
-from __future__ import absolute_import, unicode_literals
import datetime
@@ -14,7 +13,7 @@ metadata = MetaData()
ModelBase = declarative_base(metadata=metadata, class_registry=class_registry)
-class Queue(object):
+class Queue:
"""The queue class."""
__table_args__ = {'sqlite_autoincrement': True, 'mysql_engine': 'InnoDB'}
@@ -27,14 +26,14 @@ class Queue(object):
self.name = name
def __str__(self):
- return '<Queue({self.name})>'.format(self=self)
+ return f'<Queue({self.name})>'
@declared_attr
def messages(cls):
return relation('Message', backref='queue', lazy='noload')
-class Message(object):
+class Message:
"""The message class."""
__table_args__ = (
diff --git a/kombu/transport/virtual/__init__.py b/kombu/transport/virtual/__init__.py
index e2ee0b5d..579b87bf 100644
--- a/kombu/transport/virtual/__init__.py
+++ b/kombu/transport/virtual/__init__.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from .base import (
Base64, NotEquivalentError, UndeliverableWarning, BrokerState,
QoS, Message, AbstractChannel, Channel, Management, Transport,
diff --git a/kombu/transport/virtual/base.py b/kombu/transport/virtual/base.py
index c50a764e..9e496a32 100644
--- a/kombu/transport/virtual/base.py
+++ b/kombu/transport/virtual/base.py
@@ -2,7 +2,6 @@
Emulates the AMQ API for non-AMQ transports.
"""
-from __future__ import absolute_import, print_function, unicode_literals
import base64
import socket
@@ -61,7 +60,7 @@ queue_binding_t = namedtuple('queue_binding_t', (
))
-class Base64(object):
+class Base64:
"""Base64 codec."""
def encode(self, s):
@@ -79,7 +78,7 @@ class UndeliverableWarning(UserWarning):
"""The message could not be delivered to a queue."""
-class BrokerState(object):
+class BrokerState:
"""Broker state holds exchanges, queues and bindings."""
#: Mapping of exchange name to
@@ -149,7 +148,7 @@ class BrokerState(object):
)
-class QoS(object):
+class QoS:
"""Quality of Service guarantees.
Only supports `prefetch_count` at this point.
@@ -315,7 +314,7 @@ class Message(base.Message):
body = payload.get('body')
if body:
body = channel.decode_body(body, properties.get('body_encoding'))
- super(Message, self).__init__(
+ super().__init__(
body=body,
channel=channel,
delivery_tag=properties['delivery_tag'],
@@ -343,7 +342,7 @@ class Message(base.Message):
}
-class AbstractChannel(object):
+class AbstractChannel:
"""Abstract channel interface.
This is an abstract class defining the channel methods
@@ -470,7 +469,7 @@ class Channel(AbstractChannel, base.StdChannel):
self.channel_id = self.connection._avail_channel_ids.pop()
except IndexError:
raise ResourceError(
- 'No free channel ids, current={0}, channel_max={1}'.format(
+ 'No free channel ids, current={}, channel_max={}'.format(
len(self.connection.channels),
self.connection.channel_max), (20, 10),
)
@@ -491,7 +490,7 @@ class Channel(AbstractChannel, base.StdChannel):
if passive:
if exchange not in self.state.exchanges:
raise ChannelError(
- 'NOT_FOUND - no exchange {0!r} in vhost {1!r}'.format(
+ 'NOT_FOUND - no exchange {!r} in vhost {!r}'.format(
exchange, self.connection.client.virtual_host or '/'),
(50, 10), 'Channel.exchange_declare', '404',
)
@@ -523,7 +522,7 @@ class Channel(AbstractChannel, base.StdChannel):
queue = queue or 'amq.gen-%s' % uuid()
if passive and not self._has_queue(queue, **kwargs):
raise ChannelError(
- 'NOT_FOUND - no queue {0!r} in vhost {1!r}'.format(
+ 'NOT_FOUND - no queue {!r} in vhost {!r}'.format(
queue, self.connection.client.virtual_host or '/'),
(50, 10), 'Channel.queue_declare', '404',
)
@@ -853,7 +852,7 @@ class Management(base.Management):
"""Base class for the AMQP management API."""
def __init__(self, transport):
- super(Management, self).__init__(transport)
+ super().__init__(transport)
self.channel = transport.client.channel()
def get_bindings(self):
@@ -972,7 +971,7 @@ class Transport(base.Transport):
def _deliver(self, message, queue):
if not queue:
raise KeyError(
- 'Received message without destination queue: {0}'.format(
+ 'Received message without destination queue: {}'.format(
message))
try:
callback = self._callbacks[queue]
@@ -993,7 +992,7 @@ class Transport(base.Transport):
def on_message_ready(self, channel, message, queue):
if not queue or queue not in self._callbacks:
raise KeyError(
- 'Message for queue {0!r} without consumers: {1}'.format(
+ 'Message for queue {!r} without consumers: {}'.format(
queue, message))
self._callbacks[queue](message)
diff --git a/kombu/transport/virtual/exchange.py b/kombu/transport/virtual/exchange.py
index 51909a1d..c6b6161c 100644
--- a/kombu/transport/virtual/exchange.py
+++ b/kombu/transport/virtual/exchange.py
@@ -3,14 +3,13 @@
Implementations of the standard exchanges defined
by the AMQ protocol (excluding the `headers` exchange).
"""
-from __future__ import absolute_import, unicode_literals
import re
from kombu.utils.text import escape_regex
-class ExchangeType(object):
+class ExchangeType:
"""Base class for exchanges.
Implements the specifics for an exchange type.
diff --git a/kombu/transport/zookeeper.py b/kombu/transport/zookeeper.py
index d00c60e3..4abf1163 100644
--- a/kombu/transport/zookeeper.py
+++ b/kombu/transport/zookeeper.py
@@ -21,7 +21,6 @@ This queue does not offer reliable consumption. An entry is removed from
the queue prior to being processed. So if an error occurs, the consumer
has to re-queue the item or it will be lost.
"""
-from __future__ import absolute_import, unicode_literals
import os
import socket
@@ -82,7 +81,7 @@ class Channel(virtual.Channel):
_queues = {}
def __init__(self, connection, **kwargs):
- super(Channel, self).__init__(connection, **kwargs)
+ super().__init__(connection, **kwargs)
vhost = self.connection.client.virtual_host
self._vhost = '/{}'.format(vhost.strip('/'))
@@ -165,7 +164,7 @@ class Channel(virtual.Channel):
host_port = (conninfo.hostname, conninfo.port or DEFAULT_PORT)
if host_port not in hosts:
hosts.insert(0, host_port)
- conn_str = ','.join(['%s:%s' % (h, p) for h, p in hosts])
+ conn_str = ','.join([f'{h}:{p}' for h, p in hosts])
conn = KazooClient(conn_str)
conn.start()
return conn
@@ -196,7 +195,7 @@ class Transport(virtual.Transport):
if kazoo is None:
raise ImportError('The kazoo library is not installed')
- super(Transport, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
def driver_version(self):
return kazoo.__version__
diff --git a/kombu/utils/__init__.py b/kombu/utils/__init__.py
index da984d68..9f9413fe 100644
--- a/kombu/utils/__init__.py
+++ b/kombu/utils/__init__.py
@@ -1,5 +1,4 @@
"""DEPRECATED - Import from modules below."""
-from __future__ import absolute_import, print_function, unicode_literals
from .collections import EqualityDict
from .compat import fileno, maybe_fileno, nested, register_after_fork
diff --git a/kombu/utils/amq_manager.py b/kombu/utils/amq_manager.py
index 1b893635..7491bb25 100644
--- a/kombu/utils/amq_manager.py
+++ b/kombu/utils/amq_manager.py
@@ -1,5 +1,4 @@
"""AMQP Management API utilities."""
-from __future__ import absolute_import, unicode_literals
def get_manager(client, hostname=None, port=None, userid=None,
@@ -17,4 +16,4 @@ def get_manager(client, hostname=None, port=None, userid=None,
port = port if port is not None else opt('manager_port', 15672)
userid = get('userid', userid, 'guest')
password = get('password', password, 'guest')
- return pyrabbit.Client('%s:%s' % (host, port), userid, password)
+ return pyrabbit.Client(f'{host}:{port}', userid, password)
diff --git a/kombu/utils/collections.py b/kombu/utils/collections.py
index 105cc47d..0ee27399 100644
--- a/kombu/utils/collections.py
+++ b/kombu/utils/collections.py
@@ -1,5 +1,4 @@
"""Custom maps, sequences, etc."""
-from __future__ import absolute_import, unicode_literals
class HashedSeq(list):
diff --git a/kombu/utils/compat.py b/kombu/utils/compat.py
index a741c435..f5ee70eb 100644
--- a/kombu/utils/compat.py
+++ b/kombu/utils/compat.py
@@ -1,5 +1,4 @@
"""Python Compatibility Utilities."""
-from __future__ import absolute_import, unicode_literals
import numbers
import sys
diff --git a/kombu/utils/debug.py b/kombu/utils/debug.py
index 3b3453b5..2ddaa524 100644
--- a/kombu/utils/debug.py
+++ b/kombu/utils/debug.py
@@ -1,5 +1,4 @@
"""Debugging support."""
-from __future__ import absolute_import, unicode_literals
import logging
@@ -21,7 +20,7 @@ def setup_logging(loglevel=logging.DEBUG, loggers=None):
@python_2_unicode_compatible
-class Logwrapped(object):
+class Logwrapped:
"""Wrap all object methods, to log on call."""
__ignore = ('__enter__', '__exit__')
@@ -42,13 +41,13 @@ class Logwrapped(object):
info = ''
if self.ident:
info += self.ident.format(self.instance)
- info += '{0.__name__}('.format(meth)
+ info += f'{meth.__name__}('
if args:
info += ', '.join(map(repr, args))
if kwargs:
if args:
info += ', '
- info += ', '.join('{k}={v!r}'.format(k=key, v=value)
+ info += ', '.join(f'{key}={value!r}'
for key, value in items(kwargs))
info += ')'
self.logger.debug(info)
diff --git a/kombu/utils/div.py b/kombu/utils/div.py
index db52048c..aa33532e 100644
--- a/kombu/utils/div.py
+++ b/kombu/utils/div.py
@@ -1,5 +1,4 @@
"""Div. Utilities."""
-from __future__ import absolute_import, unicode_literals, print_function
from .encoding import default_encode
@@ -16,7 +15,7 @@ def emergency_dump_state(state, open_file=open, dump=None, stderr=None):
import pickle
dump = pickle.dump
persist = mktemp()
- print('EMERGENCY DUMP STATE TO FILE -> {0} <-'.format(persist), # noqa
+ print(f'EMERGENCY DUMP STATE TO FILE -> {persist} <-', # noqa
file=stderr)
fh = open_file(persist, 'w')
try:
@@ -24,7 +23,7 @@ def emergency_dump_state(state, open_file=open, dump=None, stderr=None):
dump(state, fh, protocol=0)
except Exception as exc:
print( # noqa
- 'Cannot pickle state: {0!r}. Fallback to pformat.'.format(exc),
+ f'Cannot pickle state: {exc!r}. Fallback to pformat.',
file=stderr,
)
fh.write(default_encode(pformat(state)))
diff --git a/kombu/utils/encoding.py b/kombu/utils/encoding.py
index 551cf5f3..5d3e1efb 100644
--- a/kombu/utils/encoding.py
+++ b/kombu/utils/encoding.py
@@ -1,11 +1,9 @@
-# -*- coding: utf-8 -*-
"""Text encoding utilities.
Utilities to encode text, and to safely emit text from running
applications without crashing from the infamous
:exc:`UnicodeDecodeError` exception.
"""
-from __future__ import absolute_import, unicode_literals
import sys
import traceback
@@ -118,7 +116,7 @@ if PY3: # pragma: no cover
try:
return str(s)
except Exception as exc:
- return '<Unrepresentable {0!r}: {1!r} {2!r}>'.format(
+ return '<Unrepresentable {!r}: {!r} {!r}>'.format(
type(s), exc, '\n'.join(traceback.format_stack()))
else:
def _ensure_str(s, encoding, errors):
@@ -135,7 +133,7 @@ else:
encoding, errors)
return unicode(s, encoding, errors)
except Exception as exc:
- return '<Unrepresentable {0!r}: {1!r} {2!r}>'.format(
+ return '<Unrepresentable {!r}: {!r} {!r}>'.format(
type(s), exc, '\n'.join(traceback.format_stack()))
diff --git a/kombu/utils/eventio.py b/kombu/utils/eventio.py
index 9bb4544a..d6149f7e 100644
--- a/kombu/utils/eventio.py
+++ b/kombu/utils/eventio.py
@@ -1,5 +1,4 @@
"""Selector Utilities."""
-from __future__ import absolute_import, unicode_literals
import errno
import math
@@ -57,7 +56,7 @@ except AttributeError:
SELECT_BAD_FD = {errno.EBADF}
-class _epoll(object):
+class _epoll:
def __init__(self):
self._epoll = epoll()
@@ -73,9 +72,9 @@ class _epoll(object):
def unregister(self, fd):
try:
self._epoll.unregister(fd)
- except (socket.error, ValueError, KeyError, TypeError):
+ except (OSError, ValueError, KeyError, TypeError):
pass
- except (IOError, OSError) as exc:
+ except OSError as exc:
if getattr(exc, 'errno', None) not in (errno.ENOENT, errno.EPERM):
raise
@@ -90,7 +89,7 @@ class _epoll(object):
self._epoll.close()
-class _kqueue(object):
+class _kqueue:
w_fflags = (KQ_NOTE_WRITE | KQ_NOTE_EXTEND |
KQ_NOTE_ATTRIB | KQ_NOTE_DELETE)
@@ -110,7 +109,7 @@ class _kqueue(object):
if events:
try:
self._control(fd, events, KQ_EV_DELETE)
- except socket.error:
+ except OSError:
pass
def watch_file(self, fd):
@@ -177,7 +176,7 @@ class _kqueue(object):
self._kqueue.close()
-class _poll(object):
+class _poll:
def __init__(self):
self._poller = xpoll()
@@ -200,7 +199,7 @@ class _poll(object):
def unregister(self, fd):
try:
fd = fileno(fd)
- except socket.error as exc:
+ except OSError as exc:
# we don't know the previous fd of this object
# but it will be removed by the next poll iteration.
if getattr(exc, 'errno', None) in SELECT_BAD_FD:
@@ -215,7 +214,7 @@ class _poll(object):
timeout = 0 if timeout and timeout < 0 else round((timeout or 0) * 1e3)
try:
event_list = self._quick_poll(timeout)
- except (_selecterr, socket.error) as exc:
+ except (_selecterr, OSError) as exc:
if getattr(exc, 'errno', None) == errno.EINTR:
return
raise
@@ -239,7 +238,7 @@ class _poll(object):
self._poller = None
-class _select(object):
+class _select:
def __init__(self):
self._all = (self._rfd,
@@ -260,14 +259,14 @@ class _select(object):
for fd in self._rfd | self._wfd | self._efd:
try:
_selectf([fd], [], [], 0)
- except (_selecterr, socket.error) as exc:
+ except (_selecterr, OSError) as exc:
if getattr(exc, 'errno', None) in SELECT_BAD_FD:
self.unregister(fd)
def unregister(self, fd):
try:
fd = fileno(fd)
- except socket.error as exc:
+ except OSError as exc:
# we don't know the previous fd of this object
# but it will be removed by the next poll iteration.
if getattr(exc, 'errno', None) in SELECT_BAD_FD:
@@ -282,7 +281,7 @@ class _select(object):
read, write, error = _selectf(
self._rfd, self._wfd, self._efd, timeout,
)
- except (_selecterr, socket.error) as exc:
+ except (_selecterr, OSError) as exc:
if getattr(exc, 'errno', None) == errno.EINTR:
return
elif getattr(exc, 'errno', None) in SELECT_BAD_FD:
diff --git a/kombu/utils/functional.py b/kombu/utils/functional.py
index b191a759..52e9aa1e 100644
--- a/kombu/utils/functional.py
+++ b/kombu/utils/functional.py
@@ -1,5 +1,4 @@
"""Functional Utilities."""
-from __future__ import absolute_import, unicode_literals
import random
import sys
@@ -33,7 +32,7 @@ KEYWORD_MARK = object()
@python_2_unicode_compatible
-class ChannelPromise(object):
+class ChannelPromise:
def __init__(self, contract):
self.__contract__ = contract
@@ -49,7 +48,7 @@ class ChannelPromise(object):
try:
return repr(self.__value__)
except AttributeError:
- return '<promise: 0x{0:x}>'.format(id(self.__contract__))
+ return '<promise: 0x{:x}>'.format(id(self.__contract__))
class LRUCache(UserDict):
@@ -191,7 +190,7 @@ def memoize(maxsize=None, keyfun=None, Cache=LRUCache):
@python_2_unicode_compatible
-class lazy(object):
+class lazy:
"""Holds lazy evaluation.
Evaluated when called or if the :meth:`evaluate` method is called.
@@ -366,7 +365,7 @@ def reprkwargs(kwargs, sep=', ', fmt='{0}={1}'):
def reprcall(name, args=(), kwargs=None, sep=', '):
kwargs = {} if not kwargs else kwargs
- return '{0}({1}{2}{3})'.format(
+ return '{}({}{}{})'.format(
name, sep.join(map(_safe_repr, args or ())),
(args and kwargs) and sep or '',
reprkwargs(kwargs, sep),
diff --git a/kombu/utils/imports.py b/kombu/utils/imports.py
index cb2de8c5..51024739 100644
--- a/kombu/utils/imports.py
+++ b/kombu/utils/imports.py
@@ -1,5 +1,4 @@
"""Import related utilities."""
-from __future__ import absolute_import, unicode_literals
import importlib
import sys
@@ -57,7 +56,7 @@ def symbol_by_name(name, aliases=None, imp=None, package=None,
module = imp(module_name, package=package, **kwargs)
except ValueError as exc:
reraise(ValueError,
- ValueError("Couldn't import {0!r}: {1}".format(name, exc)),
+ ValueError(f"Couldn't import {name!r}: {exc}"),
sys.exc_info()[2])
return getattr(module, cls_name) if cls_name else module
except (ImportError, AttributeError):
diff --git a/kombu/utils/json.py b/kombu/utils/json.py
index 09756ef7..4a0f1114 100644
--- a/kombu/utils/json.py
+++ b/kombu/utils/json.py
@@ -1,6 +1,4 @@
-# -*- coding: utf-8 -*-
"""JSON Serialization Utilities."""
-from __future__ import absolute_import, unicode_literals
import datetime
import decimal
@@ -12,7 +10,7 @@ from kombu.five import PY3, buffer_t, text_t, bytes_t
try:
from django.utils.functional import Promise as DjangoPromise
except ImportError: # pragma: no cover
- class DjangoPromise(object): # noqa
+ class DjangoPromise: # noqa
"""Dummy object."""
try:
@@ -56,7 +54,7 @@ class JSONEncoder(_encoder_cls):
return o.isoformat()
elif isinstance(o, textual):
return text_t(o)
- return super(JSONEncoder, self).default(o)
+ return super().default(o)
_default_encoder = JSONEncoder
diff --git a/kombu/utils/limits.py b/kombu/utils/limits.py
index 4c848340..a18149b1 100644
--- a/kombu/utils/limits.py
+++ b/kombu/utils/limits.py
@@ -1,5 +1,4 @@
"""Token bucket implementation for rate limiting."""
-from __future__ import absolute_import, unicode_literals
from collections import deque
@@ -8,7 +7,7 @@ from kombu.five import monotonic
__all__ = ('TokenBucket',)
-class TokenBucket(object):
+class TokenBucket:
"""Token Bucket Algorithm.
See Also:
diff --git a/kombu/utils/objects.py b/kombu/utils/objects.py
index dced5c5e..4f220439 100644
--- a/kombu/utils/objects.py
+++ b/kombu/utils/objects.py
@@ -1,8 +1,7 @@
"""Object Utilities."""
-from __future__ import absolute_import, unicode_literals
-class cached_property(object):
+class cached_property:
"""Cached property descriptor.
Caches the return value of the get method on first call.
diff --git a/kombu/utils/scheduling.py b/kombu/utils/scheduling.py
index 9bc4d936..22b6733b 100644
--- a/kombu/utils/scheduling.py
+++ b/kombu/utils/scheduling.py
@@ -1,5 +1,4 @@
"""Scheduling Utilities."""
-from __future__ import absolute_import, unicode_literals
from itertools import count
@@ -19,7 +18,7 @@ CYCLE_ALIASES = {
@python_2_unicode_compatible
-class FairCycle(object):
+class FairCycle:
"""Cycle between resources.
Consume from a set of resources, where each resource gets
@@ -69,7 +68,7 @@ class FairCycle(object):
self=self, size=len(self.resources))
-class round_robin_cycle(object):
+class round_robin_cycle:
"""Iterator that cycles between items in round-robin."""
def __init__(self, it=None):
diff --git a/kombu/utils/text.py b/kombu/utils/text.py
index bfaec1ee..30eb5497 100644
--- a/kombu/utils/text.py
+++ b/kombu/utils/text.py
@@ -1,8 +1,6 @@
-# -*- coding: utf-8 -*-
"""Text Utilities."""
# flake8: noqa
-from __future__ import absolute_import, unicode_literals
from difflib import SequenceMatcher
diff --git a/kombu/utils/time.py b/kombu/utils/time.py
index e1f8899e..863f4017 100644
--- a/kombu/utils/time.py
+++ b/kombu/utils/time.py
@@ -1,7 +1,6 @@
"""Time Utilities."""
# flake8: noqa
-from __future__ import absolute_import, unicode_literals
__all__ = ('maybe_s_to_ms',)
diff --git a/kombu/utils/url.py b/kombu/utils/url.py
index 16a050c4..17c8a7e8 100644
--- a/kombu/utils/url.py
+++ b/kombu/utils/url.py
@@ -1,7 +1,6 @@
"""URL Utilities."""
# flake8: noqa
-from __future__ import absolute_import, unicode_literals
try:
from collections.abc import Mapping
@@ -89,7 +88,7 @@ def as_url(scheme, host=None, port=None, user=None, password=None,
path=None, query=None, sanitize=False, mask='**'):
# type: (str, str, int, str, str, str, str, bool, str) -> str
"""Generate URL from component parts."""
- parts = ['{0}://'.format(scheme)]
+ parts = [f'{scheme}://']
if user or password:
if user:
parts.append(safequote(user))
diff --git a/kombu/utils/uuid.py b/kombu/utils/uuid.py
index 341475bf..010b3440 100644
--- a/kombu/utils/uuid.py
+++ b/kombu/utils/uuid.py
@@ -1,5 +1,4 @@
"""UUID utilities."""
-from __future__ import absolute_import, unicode_literals
from uuid import uuid4
diff --git a/setup.py b/setup.py
index c47d9ce1..03b4cdba 100644
--- a/setup.py
+++ b/setup.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
import os
import re
import sys
diff --git a/t/integration/__init__.py b/t/integration/__init__.py
index 8131c98c..1bea4880 100644
--- a/t/integration/__init__.py
+++ b/t/integration/__init__.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import os
import sys
diff --git a/t/integration/common.py b/t/integration/common.py
index 19dca984..a749bb60 100644
--- a/t/integration/common.py
+++ b/t/integration/common.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import socket
from contextlib import closing
from time import sleep
@@ -8,7 +6,7 @@ import pytest
import kombu
-class BasicFunctionality(object):
+class BasicFunctionality:
def test_connect(self, connection):
assert connection.connect()
@@ -127,7 +125,7 @@ class BasicFunctionality(object):
message.ack()
-class BaseExchangeTypes(object):
+class BaseExchangeTypes:
def _callback(self, body, message):
message.ack()
@@ -215,7 +213,7 @@ class BaseExchangeTypes(object):
self._consume(conn, test_queue3)
-class BaseTimeToLive(object):
+class BaseTimeToLive:
def test_publish_consume(self, connection):
test_queue = kombu.Queue('ttl_test', routing_key='ttl_test')
@@ -263,7 +261,7 @@ class BaseTimeToLive(object):
buf.get(timeout=1)
-class BasePriority(object):
+class BasePriority:
PRIORITY_ORDER = 'asc'
@@ -386,15 +384,15 @@ class BasePriority(object):
class BaseFailover(BasicFunctionality):
def test_connect(self, failover_connection):
- super(BaseFailover, self).test_connect(failover_connection)
+ super().test_connect(failover_connection)
def test_publish_consume(self, failover_connection):
- super(BaseFailover, self).test_publish_consume(failover_connection)
+ super().test_publish_consume(failover_connection)
def test_consume_empty_queue(self, failover_connection):
- super(BaseFailover, self).test_consume_empty_queue(failover_connection)
+ super().test_consume_empty_queue(failover_connection)
def test_simple_buffer_publish_consume(self, failover_connection):
- super(BaseFailover, self).test_simple_buffer_publish_consume(
+ super().test_simple_buffer_publish_consume(
failover_connection
)
diff --git a/t/integration/test_py_amqp.py b/t/integration/test_py_amqp.py
index 93327c8a..da21be40 100644
--- a/t/integration/test_py_amqp.py
+++ b/t/integration/test_py_amqp.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import os
import pytest
@@ -12,12 +10,12 @@ from .common import (
def get_connection(hostname, port, vhost):
- return kombu.Connection('pyamqp://{}:{}'.format(hostname, port))
+ return kombu.Connection(f'pyamqp://{hostname}:{port}')
def get_failover_connection(hostname, port, vhost):
return kombu.Connection(
- 'pyamqp://localhost:12345;pyamqp://{}:{}'.format(hostname, port)
+ f'pyamqp://localhost:12345;pyamqp://{hostname}:{port}'
)
diff --git a/t/integration/test_redis.py b/t/integration/test_redis.py
index e4666d12..459f0892 100644
--- a/t/integration/test_redis.py
+++ b/t/integration/test_redis.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import os
import pytest
@@ -13,7 +11,7 @@ from .common import (
def get_connection(
hostname, port, vhost):
- return kombu.Connection('redis://{}:{}'.format(hostname, port))
+ return kombu.Connection(f'redis://{hostname}:{port}')
@pytest.fixture()
diff --git a/t/mocks.py b/t/mocks.py
index ef74974b..42314915 100644
--- a/t/mocks.py
+++ b/t/mocks.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from itertools import count
from case import ContextMock, Mock
@@ -21,7 +19,7 @@ def PromiseMock(*args, **kwargs):
return m
-class MockPool(object):
+class MockPool:
def __init__(self, value=None):
self.value = value or ContextMock()
@@ -34,12 +32,12 @@ class Message(base.Message):
def __init__(self, *args, **kwargs):
self.throw_decode_error = kwargs.get('throw_decode_error', False)
- super(Message, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
def decode(self):
if self.throw_decode_error:
raise ValueError("can't decode message")
- return super(Message, self).decode()
+ return super().decode()
class Channel(base.StdChannel):
@@ -147,7 +145,7 @@ class Channel(base.StdChannel):
self._called('basic_qos')
-class Connection(object):
+class Connection:
connected = True
def __init__(self, client):
diff --git a/t/unit/__init__.py b/t/unit/__init__.py
index 01e6d4f4..e69de29b 100644
--- a/t/unit/__init__.py
+++ b/t/unit/__init__.py
@@ -1 +0,0 @@
-from __future__ import absolute_import, unicode_literals
diff --git a/t/unit/asynchronous/aws/case.py b/t/unit/asynchronous/aws/case.py
index 70d9565f..1a6322f8 100644
--- a/t/unit/asynchronous/aws/case.py
+++ b/t/unit/asynchronous/aws/case.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import skip
@@ -10,5 +7,5 @@ from case import skip
@skip.unless_module('boto3')
@skip.unless_module('pycurl')
@pytest.mark.usefixtures('hub')
-class AWSCase(object):
+class AWSCase:
pass
diff --git a/t/unit/asynchronous/aws/sqs/test_connection.py b/t/unit/asynchronous/aws/sqs/test_connection.py
index 9d1038fc..07c76475 100644
--- a/t/unit/asynchronous/aws/sqs/test_connection.py
+++ b/t/unit/asynchronous/aws/sqs/test_connection.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
from case import Mock, MagicMock
from kombu.asynchronous.aws.sqs.connection import (
diff --git a/t/unit/asynchronous/aws/sqs/test_queue.py b/t/unit/asynchronous/aws/sqs/test_queue.py
index add591df..08b16ef7 100644
--- a/t/unit/asynchronous/aws/sqs/test_queue.py
+++ b/t/unit/asynchronous/aws/sqs/test_queue.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
@@ -89,7 +86,7 @@ class test_AsyncQueue(AWSCase):
self.callback.assert_called_with(messages[0])
def MockMessage(self, id, md5):
- m = Mock(name='Message-{0}'.format(id))
+ m = Mock(name=f'Message-{id}')
m.id = id
m.md5 = md5
return m
diff --git a/t/unit/asynchronous/aws/test_aws.py b/t/unit/asynchronous/aws/test_aws.py
index d0e98b70..09d731fa 100644
--- a/t/unit/asynchronous/aws/test_aws.py
+++ b/t/unit/asynchronous/aws/test_aws.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
from case import Mock
from kombu.asynchronous.aws import connect_sqs
diff --git a/t/unit/asynchronous/aws/test_connection.py b/t/unit/asynchronous/aws/test_connection.py
index 79966a85..f557bd2e 100644
--- a/t/unit/asynchronous/aws/test_connection.py
+++ b/t/unit/asynchronous/aws/test_connection.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
import pytest
from contextlib import contextmanager
diff --git a/t/unit/asynchronous/http/test_curl.py b/t/unit/asynchronous/http/test_curl.py
index d38a819f..7aff9a6e 100644
--- a/t/unit/asynchronous/http/test_curl.py
+++ b/t/unit/asynchronous/http/test_curl.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock, call, patch, skip
diff --git a/t/unit/asynchronous/http/test_http.py b/t/unit/asynchronous/http/test_http.py
index 21c66b97..39d559e0 100644
--- a/t/unit/asynchronous/http/test_http.py
+++ b/t/unit/asynchronous/http/test_http.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from io import BytesIO
diff --git a/t/unit/asynchronous/test_hub.py b/t/unit/asynchronous/test_hub.py
index 044a3111..659fafca 100644
--- a/t/unit/asynchronous/test_hub.py
+++ b/t/unit/asynchronous/test_hub.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import errno
import pytest
@@ -16,7 +14,7 @@ from kombu.asynchronous.hub import (
from kombu.asynchronous.semaphore import DummyLock, LaxBoundedSemaphore
-class File(object):
+class File:
def __init__(self, fd):
self.fd = fd
@@ -237,7 +235,7 @@ class test_Hub:
poller = self.hub.poller
self.hub.stop()
mock_callback = Mock()
- self.hub._ready = set([mock_callback])
+ self.hub._ready = {mock_callback}
self.hub.close()
poller.close.assert_called_with()
mock_callback.assert_called_once_with()
diff --git a/t/unit/asynchronous/test_semaphore.py b/t/unit/asynchronous/test_semaphore.py
index 86f58cce..8767ca91 100644
--- a/t/unit/asynchronous/test_semaphore.py
+++ b/t/unit/asynchronous/test_semaphore.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.asynchronous.semaphore import LaxBoundedSemaphore
diff --git a/t/unit/asynchronous/test_timer.py b/t/unit/asynchronous/test_timer.py
index e9bbec0f..733e106b 100644
--- a/t/unit/asynchronous/test_timer.py
+++ b/t/unit/asynchronous/test_timer.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from datetime import datetime
diff --git a/t/unit/conftest.py b/t/unit/conftest.py
index c7224ce5..638fa9aa 100644
--- a/t/unit/conftest.py
+++ b/t/unit/conftest.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import atexit
import os
import pytest
@@ -72,7 +70,7 @@ def find_distribution_modules(name=__name__, file=__file__):
def import_all_modules(name=__name__, file=__file__, skip=[]):
for module in find_distribution_modules(name, file):
if module not in skip:
- print('preimporting %r for coverage...' % (module,))
+ print(f'preimporting {module!r} for coverage...')
try:
__import__(module)
except (ImportError, VersionMismatch, AttributeError):
diff --git a/t/unit/test_clocks.py b/t/unit/test_clocks.py
index 5ed30bf1..a31aea32 100644
--- a/t/unit/test_clocks.py
+++ b/t/unit/test_clocks.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pickle
from heapq import heappush
diff --git a/t/unit/test_common.py b/t/unit/test_common.py
index 42fac679..827b4265 100644
--- a/t/unit/test_common.py
+++ b/t/unit/test_common.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import socket
@@ -333,7 +331,7 @@ class test_insured:
conn.ensure_connection.assert_called_with(errback=custom_errback)
-class MockConsumer(object):
+class MockConsumer:
consumers = set()
def __init__(self, channel, queues=None, callbacks=None, **kwargs):
@@ -351,7 +349,7 @@ class MockConsumer(object):
class test_itermessages:
- class MockConnection(object):
+ class MockConnection:
should_raise_timeout = False
def drain_events(self, **kwargs):
diff --git a/t/unit/test_compat.py b/t/unit/test_compat.py
index 485625d0..26d55138 100644
--- a/t/unit/test_compat.py
+++ b/t/unit/test_compat.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock, patch
@@ -14,14 +12,14 @@ class test_misc:
def test_iterconsume(self):
- class MyConnection(object):
+ class MyConnection:
drained = 0
def drain_events(self, *args, **kwargs):
self.drained += 1
return self.drained
- class Consumer(object):
+ class Consumer:
active = False
def consume(self, *args, **kwargs):
@@ -238,8 +236,7 @@ class test_Consumer:
class C(compat.Consumer):
def iterconsume(self, limit=None):
- for i in range(limit):
- yield i
+ yield from range(limit)
c = C(self.connection,
queue=n, exchange=n, routing_key='rkey')
diff --git a/t/unit/test_compression.py b/t/unit/test_compression.py
index 972d8268..eed29d1e 100644
--- a/t/unit/test_compression.py
+++ b/t/unit/test_compression.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import sys
diff --git a/t/unit/test_connection.py b/t/unit/test_connection.py
index 21cfeb41..866240cd 100644
--- a/t/unit/test_connection.py
+++ b/t/unit/test_connection.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pickle
import pytest
import socket
diff --git a/t/unit/test_entity.py b/t/unit/test_entity.py
index c44c0677..494f3124 100644
--- a/t/unit/test_entity.py
+++ b/t/unit/test_entity.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pickle
import pytest
@@ -71,7 +69,7 @@ class test_Exchange:
bound = exchange.bind(chan)
assert bound.is_bound
assert bound.channel is chan
- assert 'bound to chan:%r' % (chan.channel_id,) in repr(bound)
+ assert f'bound to chan:{chan.channel_id!r}' in repr(bound)
def test_hash(self):
assert hash(Exchange('a')) == hash(Exchange('a'))
@@ -220,7 +218,7 @@ class test_Queue:
assert queue.exchange == exchange
def test_constructor_with_string_exchange(self):
- exchange_name = str('exchange_name')
+ exchange_name = 'exchange_name'
queue = Queue(name='queue_name', exchange=exchange_name)
assert queue.exchange == Exchange(exchange_name)
diff --git a/t/unit/test_exceptions.py b/t/unit/test_exceptions.py
index f72f3d6d..d7002d2f 100644
--- a/t/unit/test_exceptions.py
+++ b/t/unit/test_exceptions.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from case import Mock
from kombu.exceptions import HttpError
diff --git a/t/unit/test_log.py b/t/unit/test_log.py
index 772b520d..5da579d3 100644
--- a/t/unit/test_log.py
+++ b/t/unit/test_log.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import logging
import sys
diff --git a/t/unit/test_matcher.py b/t/unit/test_matcher.py
index 8433a19f..0428ee15 100644
--- a/t/unit/test_matcher.py
+++ b/t/unit/test_matcher.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.matcher import (
match, register, registry, unregister, fnmatch, rematch,
MatcherNotInstalled
@@ -8,7 +6,7 @@ from kombu.matcher import (
import pytest
-class test_Matcher(object):
+class test_Matcher:
def test_register_match_unregister_matcher(self):
register("test_matcher", rematch)
diff --git a/t/unit/test_message.py b/t/unit/test_message.py
index c7d2b5f5..067f15f5 100644
--- a/t/unit/test_message.py
+++ b/t/unit/test_message.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import sys
diff --git a/t/unit/test_messaging.py b/t/unit/test_messaging.py
index 7ca790c9..ed8e9a82 100644
--- a/t/unit/test_messaging.py
+++ b/t/unit/test_messaging.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pickle
import pytest
import sys
@@ -97,7 +95,7 @@ class test_Producer:
assert json.loads(zlib.decompress(m).decode('utf-8')) == message
def test_prepare_custom_content_type(self):
- message = 'the quick brown fox'.encode('utf-8')
+ message = b'the quick brown fox'
channel = self.connection.channel()
p = Producer(channel, self.exchange, serializer='json')
m, ctype, cencoding = p._prepare(message, content_type='custom')
diff --git a/t/unit/test_mixins.py b/t/unit/test_mixins.py
index 372399e4..a781ca86 100644
--- a/t/unit/test_mixins.py
+++ b/t/unit/test_mixins.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import socket
@@ -71,7 +69,7 @@ class test_ConsumerMixin:
def se2(*args, **kwargs):
c.should_stop = True
- raise socket.error()
+ raise OSError()
c.connection.drain_events.side_effect = se2
it = c.consume(no_ack=True)
with pytest.raises(StopIteration):
diff --git a/t/unit/test_pidbox.py b/t/unit/test_pidbox.py
index a187af37..f10842e6 100644
--- a/t/unit/test_pidbox.py
+++ b/t/unit/test_pidbox.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import socket
import warnings
diff --git a/t/unit/test_pools.py b/t/unit/test_pools.py
index 18719688..c6e03440 100644
--- a/t/unit/test_pools.py
+++ b/t/unit/test_pools.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
diff --git a/t/unit/test_serialization.py b/t/unit/test_serialization.py
index 88af0860..02502f11 100644
--- a/t/unit/test_serialization.py
+++ b/t/unit/test_serialization.py
@@ -1,6 +1,4 @@
#!/usr/bin/python
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
import pytest
import sys
@@ -299,8 +297,8 @@ class test_Serialization:
accept=['application/x-doomsday'])
def test_raw_encode(self):
- assert raw_encode('foo'.encode('utf-8')) == (
- 'application/data', 'binary', 'foo'.encode('utf-8'),
+ assert raw_encode(b'foo') == (
+ 'application/data', 'binary', b'foo',
)
@mock.mask_modules('yaml')
diff --git a/t/unit/test_simple.py b/t/unit/test_simple.py
index 3e92566c..c86ea73c 100644
--- a/t/unit/test_simple.py
+++ b/t/unit/test_simple.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
@@ -14,7 +12,7 @@ class SimpleBase:
if not isinstance(q, Queue):
q = self.__class__.__name__
if name:
- q = '%s.%s' % (q, name)
+ q = f'{q}.{name}'
return self._Queue(q, *args, **kwargs)
def _Queue(self, *args, **kwargs):
@@ -84,8 +82,8 @@ class SimpleBase:
def test_custom_Queue(self):
n = self.__class__.__name__
- exchange = Exchange('%s-test.custom.Queue' % (n,))
- queue = Queue('%s-test.custom.Queue' % (n,),
+ exchange = Exchange(f'{n}-test.custom.Queue')
+ queue = Queue(f'{n}-test.custom.Queue',
exchange,
'my.routing.key')
diff --git a/t/unit/transport/test_SQS.py b/t/unit/transport/test_SQS.py
index 09e2dc5d..84b67a8b 100644
--- a/t/unit/transport/test_SQS.py
+++ b/t/unit/transport/test_SQS.py
@@ -5,7 +5,6 @@ http://github.com/pcsforeducation/sqs-mock-python. They have been patched
slightly.
"""
-from __future__ import absolute_import, unicode_literals
import os
import pytest
@@ -39,7 +38,7 @@ example_predefined_queues = {
}
-class SQSMessageMock(object):
+class SQSMessageMock:
def __init__(self):
"""
Imitate the SQS Message from boto3.
@@ -48,7 +47,7 @@ class SQSMessageMock(object):
self.receipt_handle = "receipt_handle_xyz"
-class QueueMock(object):
+class QueueMock:
""" Hold information about a queue. """
def __init__(self, url, creation_attributes=None):
@@ -63,7 +62,7 @@ class QueueMock(object):
return 'QueueMock: {} {} messages'.format(self.url, len(self.messages))
-class SQSClientMock(object):
+class SQSClientMock:
def __init__(self, QueueName='unittest_queue'):
"""
@@ -80,7 +79,7 @@ class SQSClientMock(object):
for q in self._queues.values():
if q.url == url:
return q
- raise Exception("Queue url {} not found".format(url))
+ raise Exception(f"Queue url {url} not found")
def create_queue(self, QueueName=None, Attributes=None):
q = self._queues[QueueName] = QueueMock(
@@ -316,7 +315,7 @@ class test_Channel:
# Now test getting many messages
for i in range(3):
- message = 'message: {0}'.format(i)
+ message = f'message: {i}'
self.producer.publish(message)
self.channel._get_bulk(self.queue_name, max_if_unlimited=3)
@@ -420,7 +419,7 @@ class test_Channel:
self.channel._get_bulk(self.queue_name)
assert self.channel.connection._deliver.call_count == 5
for i in range(5):
- self.channel.qos.append(Mock(name='message{0}'.format(i)), i)
+ self.channel.qos.append(Mock(name=f'message{i}'), i)
# Now, do the get again, the number of messages returned should be 1.
self.channel.connection._deliver.reset_mock()
@@ -643,7 +642,7 @@ class test_Channel:
# Getting many messages
for i in range(3):
- p.publish('message: {0}'.format(i))
+ p.publish(f'message: {i}')
channel.connection._deliver = Mock(name='_deliver')
channel._get_bulk(queue_name, max_if_unlimited=3)
diff --git a/t/unit/transport/test_azureservicebus.py b/t/unit/transport/test_azureservicebus.py
index d5670bba..2dd08c77 100644
--- a/t/unit/transport/test_azureservicebus.py
+++ b/t/unit/transport/test_azureservicebus.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import skip, patch
@@ -19,7 +17,7 @@ except ImportError:
ServiceBusService = Message = None
-class QueueMock(object):
+class QueueMock:
""" Hold information about a queue. """
def __init__(self, name):
@@ -53,7 +51,7 @@ def _create_mock_connection(url='', **kwargs):
return Connection(url, transport=Transport, **kwargs)
-class AzureServiceBusClientMock(object):
+class AzureServiceBusClientMock:
def __init__(self):
"""
@@ -207,7 +205,7 @@ class test_Channel:
# Test getting multiple messages
for i in range(3):
- message = 'message: {0}'.format(i)
+ message = f'message: {i}'
self.producer.publish(message)
queue_service = self.channel.queue_service
diff --git a/t/unit/transport/test_base.py b/t/unit/transport/test_base.py
index 31c2f5a9..6d8d2472 100644
--- a/t/unit/transport/test_base.py
+++ b/t/unit/transport/test_base.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
diff --git a/t/unit/transport/test_consul.py b/t/unit/transport/test_consul.py
index 43b2b165..9e1a19c7 100644
--- a/t/unit/transport/test_consul.py
+++ b/t/unit/transport/test_consul.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock, skip
diff --git a/t/unit/transport/test_etcd.py b/t/unit/transport/test_etcd.py
index b61fd7a7..d40c2101 100644
--- a/t/unit/transport/test_etcd.py
+++ b/t/unit/transport/test_etcd.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock, patch, skip
diff --git a/t/unit/transport/test_filesystem.py b/t/unit/transport/test_filesystem.py
index 52a925f0..1e574240 100644
--- a/t/unit/transport/test_filesystem.py
+++ b/t/unit/transport/test_filesystem.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import tempfile
from case import skip
diff --git a/t/unit/transport/test_librabbitmq.py b/t/unit/transport/test_librabbitmq.py
index 42829d96..ca140eb4 100644
--- a/t/unit/transport/test_librabbitmq.py
+++ b/t/unit/transport/test_librabbitmq.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock, patch, skip
diff --git a/t/unit/transport/test_memory.py b/t/unit/transport/test_memory.py
index 829b94ad..6db08827 100644
--- a/t/unit/transport/test_memory.py
+++ b/t/unit/transport/test_memory.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import socket
@@ -148,7 +146,7 @@ class test_MemoryTransport:
)
message = consumer.queues[0].get()._raw
- class Cycle(object):
+ class Cycle:
def get(self, callback, timeout=None):
return (message, 'foo'), c1
diff --git a/t/unit/transport/test_mongodb.py b/t/unit/transport/test_mongodb.py
index 7380183d..5d978764 100644
--- a/t/unit/transport/test_mongodb.py
+++ b/t/unit/transport/test_mongodb.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import datetime
import pytest
diff --git a/t/unit/transport/test_pyamqp.py b/t/unit/transport/test_pyamqp.py
index 04b7e53c..8e2e2eea 100644
--- a/t/unit/transport/test_pyamqp.py
+++ b/t/unit/transport/test_pyamqp.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import sys
from itertools import count
@@ -110,7 +108,7 @@ class test_Transport:
def test_dnspython_localhost_resolve_bug(self):
- class Conn(object):
+ class Conn:
def __init__(self, **kwargs):
vars(self).update(kwargs)
@@ -154,7 +152,7 @@ class test_pyamqp:
Connection = MockConnection
c = Connection(port=None, transport=Transport).connect()
- assert c['host'] == '127.0.0.1:%s' % (Transport.default_port,)
+ assert c['host'] == f'127.0.0.1:{Transport.default_port}'
def test_custom_port(self):
diff --git a/t/unit/transport/test_pyro.py b/t/unit/transport/test_pyro.py
index 100a4c99..a7d27324 100644
--- a/t/unit/transport/test_pyro.py
+++ b/t/unit/transport/test_pyro.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import socket
@@ -77,7 +75,7 @@ class test_PyroTransport:
)
message = consumer.queues[0].get()._raw
- class Cycle(object):
+ class Cycle:
def get(self, callback, timeout=None):
return (message, 'foo'), c1
diff --git a/t/unit/transport/test_qpid.py b/t/unit/transport/test_qpid.py
index e2999c3e..d322baf2 100644
--- a/t/unit/transport/test_qpid.py
+++ b/t/unit/transport/test_qpid.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import select
import ssl
@@ -53,7 +51,7 @@ class BreakOutException(Exception):
@skip.if_python3()
@skip.if_pypy()
-class test_QoS__init__(object):
+class test_QoS__init__:
def setup(self):
self.mock_session = Mock()
@@ -72,7 +70,7 @@ class test_QoS__init__(object):
@skip.if_python3()
@skip.if_pypy()
-class test_QoS_can_consume(object):
+class test_QoS_can_consume:
def setup(self):
session = Mock()
@@ -96,7 +94,7 @@ class test_QoS_can_consume(object):
@skip.if_python3()
@skip.if_pypy()
-class test_QoS_can_consume_max_estimate(object):
+class test_QoS_can_consume_max_estimate:
def setup(self):
self.mock_session = Mock()
@@ -114,7 +112,7 @@ class test_QoS_can_consume_max_estimate(object):
@skip.if_python3()
@skip.if_pypy()
-class test_QoS_ack(object):
+class test_QoS_ack:
def setup(self):
self.mock_session = Mock()
@@ -136,7 +134,7 @@ class test_QoS_ack(object):
@skip.if_python3()
@skip.if_pypy()
-class test_QoS_reject(object):
+class test_QoS_reject:
@pytest.fixture(autouse=True)
def setup_qpid(self, patching):
@@ -177,12 +175,12 @@ class test_QoS_reject(object):
@skip.if_python3()
@skip.if_pypy()
-class test_QoS(object):
+class test_QoS:
def mock_message_factory(self):
"""Create and return a mock message tag and delivery_tag."""
m_delivery_tag = self.delivery_tag_generator.next()
- m = 'message %s' % (m_delivery_tag, )
+ m = f'message {m_delivery_tag}'
return m, m_delivery_tag
def add_n_messages_to_qos(self, n, qos):
@@ -238,7 +236,7 @@ class test_QoS(object):
@skip.if_python3()
@skip.if_pypy()
-class ConnectionTestBase(object):
+class ConnectionTestBase:
@patch(QPID_MODULE + '.qpid')
def setup(self, mock_qpid):
@@ -410,7 +408,7 @@ class test_Connection_close(ConnectionTestBase):
class test_Connection_close_channel(ConnectionTestBase):
def setup(self):
- super(test_Connection_close_channel, self).setup()
+ super().setup()
self.conn.channels = Mock()
def test_connection_close_channel_removes_channel_from_channel_list(self):
@@ -432,7 +430,7 @@ class test_Connection_close_channel(ConnectionTestBase):
@skip.if_python3()
@skip.if_pypy()
-class ChannelTestBase(object):
+class ChannelTestBase:
@pytest.fixture(autouse=True)
def setup_channel(self, patching):
@@ -844,7 +842,7 @@ class test_Channel_queue_delete(ChannelTestBase):
@skip.if_python3()
@skip.if_pypy()
-class test_Channel(object):
+class test_Channel:
@patch(QPID_MODULE + '.qpidtoollibs')
def setup(self, mock_qpidtoollibs):
@@ -1333,7 +1331,7 @@ class test_Channel(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport__init__(object):
+class test_Transport__init__:
@pytest.fixture(autouse=True)
def mock_verify_runtime_environment(self, patching):
@@ -1362,7 +1360,7 @@ class test_Transport__init__(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_drain_events(object):
+class test_Transport_drain_events:
@pytest.fixture(autouse=True)
def setup_self(self, disable_runtime_dependency_check):
@@ -1414,7 +1412,7 @@ class test_Transport_drain_events(object):
@skip.if_python3()
@skip.if_pypy()
-class test_Transport_create_channel(object):
+class test_Transport_create_channel:
@pytest.fixture(autouse=True)
def setup_self(self, disable_runtime_dependency_check):
@@ -1439,12 +1437,12 @@ class test_Transport_create_channel(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_establish_connection(object):
+class test_Transport_establish_connection:
@pytest.fixture(autouse=True)
def setup_self(self, disable_runtime_dependency_check):
- class MockClient(object):
+ class MockClient:
pass
self.client = MockClient()
@@ -1655,7 +1653,7 @@ class test_Transport_establish_connection(object):
@skip.if_python3()
@skip.if_pypy()
-class test_Transport_class_attributes(object):
+class test_Transport_class_attributes:
def test_verify_Connection_attribute(self):
assert Connection is Transport.Connection
@@ -1692,7 +1690,7 @@ class test_Transport_class_attributes(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_register_with_event_loop(object):
+class test_Transport_register_with_event_loop:
def test_transport_register_with_event_loop_calls_add_reader(self):
transport = Transport(Mock())
@@ -1707,7 +1705,7 @@ class test_Transport_register_with_event_loop(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_Qpid_callback_handlers_async(object):
+class test_Transport_Qpid_callback_handlers_async:
@pytest.fixture(autouse=True)
def setup_self(self, patching, disable_runtime_dependency_check):
@@ -1727,7 +1725,7 @@ class test_Transport_Qpid_callback_handlers_async(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_Qpid_callback_handlers_sync(object):
+class test_Transport_Qpid_callback_handlers_sync:
@pytest.fixture(autouse=True)
def setup(self, patching, disable_runtime_dependency_check):
@@ -1746,7 +1744,7 @@ class test_Transport_Qpid_callback_handlers_sync(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_on_readable(object):
+class test_Transport_on_readable:
@pytest.fixture(autouse=True)
def setup_self(self, patching, disable_runtime_dependency_check):
@@ -1778,7 +1776,7 @@ class test_Transport_on_readable(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport_verify_runtime_environment(object):
+class test_Transport_verify_runtime_environment:
@pytest.fixture(autouse=True)
def setup_self(self, patching):
@@ -1816,7 +1814,7 @@ class test_Transport_verify_runtime_environment(object):
@skip.if_python3()
@skip.if_pypy()
@pytest.mark.usefixtures('disable_runtime_dependency_check')
-class test_Transport(object):
+class test_Transport:
def setup(self):
"""Creates a mock_client to be used in testing."""
diff --git a/t/unit/transport/test_redis.py b/t/unit/transport/test_redis.py
index a36dfc2b..05cef4b9 100644
--- a/t/unit/transport/test_redis.py
+++ b/t/unit/transport/test_redis.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import socket
import types
@@ -40,7 +38,7 @@ class ResponseError(Exception):
pass
-class Client(object):
+class Client:
queues = {}
sets = defaultdict(set)
hashes = defaultdict(dict)
@@ -143,10 +141,10 @@ class Client(object):
def _new_queue(self, key):
self.queues[key] = _Queue()
- class _sconnection(object):
+ class _sconnection:
disconnected = False
- class _socket(object):
+ class _socket:
blocking = True
filenos = count(30)
@@ -176,7 +174,7 @@ class Client(object):
def pubsub(self, *args, **kwargs):
connection = self.connection
- class ConnectionPool(object):
+ class ConnectionPool:
def get_connection(self, *args, **kwargs):
return connection
@@ -185,7 +183,7 @@ class Client(object):
return self
-class Pipeline(object):
+class Pipeline:
def __init__(self, client):
self.client = client
@@ -291,7 +289,7 @@ class test_Channel:
def __init__(self, *args, **kwargs):
self._pool = pool_at_init[0]
- super(XChannel, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
def _get_client(self):
return lambda *_, **__: client
@@ -981,7 +979,7 @@ class test_Redis:
self.queue(channel).declare()
for i in range(10):
- producer.publish({'hello': 'world-%s' % (i,)})
+ producer.publish({'hello': f'world-{i}'})
assert channel._size('test_Redis') == 10
assert self.queue(channel).purge() == 10
@@ -1075,7 +1073,7 @@ def _redis_modules():
exceptions.InvalidResponse = InvalidResponse
exceptions.ResponseError = ResponseError
- class Redis(object):
+ class Redis:
pass
myredis = types.ModuleType(bytes_if_py2('redis'))
@@ -1425,10 +1423,10 @@ class test_RedisSentinel:
connection.channel()
patched.assert_called_once_with(
[
- (u'localhost', 65532),
- (u'localhost', 65533),
- (u'localhost', 65534),
- (u'localhost', 65535),
+ ('localhost', 65532),
+ ('localhost', 65533),
+ ('localhost', 65534),
+ ('localhost', 65535),
],
connection_class=mock.ANY, db=0, max_connections=10,
min_other_sentinels=0, password=None, sentinel_kwargs=None,
@@ -1452,7 +1450,7 @@ class test_RedisSentinel:
connection.channel()
patched.assert_called_once_with(
- [(u'localhost', 65532)],
+ [('localhost', 65532)],
connection_class=mock.ANY, db=0, max_connections=10,
min_other_sentinels=0, password=None, sentinel_kwargs=None,
socket_connect_timeout=None, socket_keepalive=None,
diff --git a/t/unit/transport/test_sqlalchemy.py b/t/unit/transport/test_sqlalchemy.py
index 70235b9a..a6f8aa8f 100644
--- a/t/unit/transport/test_sqlalchemy.py
+++ b/t/unit/transport/test_sqlalchemy.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import patch, skip
diff --git a/t/unit/transport/test_transport.py b/t/unit/transport/test_transport.py
index 26df9e19..a13d7bf4 100644
--- a/t/unit/transport/test_transport.py
+++ b/t/unit/transport/test_transport.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from case import Mock, patch
from kombu import transport
diff --git a/t/unit/transport/test_zookeeper.py b/t/unit/transport/test_zookeeper.py
index 7505a6d9..2d81ffcf 100644
--- a/t/unit/transport/test_zookeeper.py
+++ b/t/unit/transport/test_zookeeper.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import skip
from kombu import Connection
diff --git a/t/unit/transport/virtual/test_base.py b/t/unit/transport/virtual/test_base.py
index 65cfa1ec..ad426ae0 100644
--- a/t/unit/transport/virtual/test_base.py
+++ b/t/unit/transport/virtual/test_base.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import io
import pytest
import warnings
@@ -117,7 +115,7 @@ class test_Message:
if message.errors:
message._reraise_error()
- assert message.body == 'the quick brown fox...'.encode('utf-8')
+ assert message.body == b'the quick brown fox...'
assert message.delivery_tag, tag
def test_create_no_body(self):
@@ -133,7 +131,7 @@ class test_Message:
tag = data['properties']['delivery_tag'] = uuid()
message = c.message_to_python(data)
dict_ = message.serializable()
- assert dict_['body'] == 'the quick brown fox...'.encode('utf-8')
+ assert dict_['body'] == b'the quick brown fox...'
assert dict_['properties']['delivery_tag'] == tag
assert 'compression' not in dict_['headers']
@@ -343,7 +341,7 @@ class test_Channel:
r1 = c.message_to_python(c.basic_get(n))
assert r1
- assert r1.body == 'nthex quick brown fox...'.encode('utf-8')
+ assert r1.body == b'nthex quick brown fox...'
assert c.basic_get(n) is None
consumer_tag = uuid()
@@ -353,7 +351,7 @@ class test_Channel:
assert n + '2' in c._active_queues
c.drain_events()
r2 = c.message_to_python(messages[-1])
- assert r2.body == 'nthex quick brown fox...'.encode('utf-8')
+ assert r2.body == b'nthex quick brown fox...'
assert r2.delivery_info['exchange'] == n
assert r2.delivery_info['routing_key'] == n
with pytest.raises(virtual.Empty):
@@ -363,7 +361,7 @@ class test_Channel:
c._restore(r2)
r3 = c.message_to_python(c.basic_get(n))
assert r3
- assert r3.body == 'nthex quick brown fox...'.encode('utf-8')
+ assert r3.body == b'nthex quick brown fox...'
assert c.basic_get(n) is None
def test_basic_ack(self):
diff --git a/t/unit/transport/virtual/test_exchange.py b/t/unit/transport/virtual/test_exchange.py
index 7b94e56c..736d03e8 100644
--- a/t/unit/transport/virtual/test_exchange.py
+++ b/t/unit/transport/virtual/test_exchange.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
diff --git a/t/unit/utils/test_amq_manager.py b/t/unit/utils/test_amq_manager.py
index 3ea1e41a..5e08cd78 100644
--- a/t/unit/utils/test_amq_manager.py
+++ b/t/unit/utils/test_amq_manager.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import mock, patch
diff --git a/t/unit/utils/test_compat.py b/t/unit/utils/test_compat.py
index 4b866db9..c4557ce2 100644
--- a/t/unit/utils/test_compat.py
+++ b/t/unit/utils/test_compat.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import socket
import sys
import types
diff --git a/t/unit/utils/test_debug.py b/t/unit/utils/test_debug.py
index 732638cb..d78d7032 100644
--- a/t/unit/utils/test_debug.py
+++ b/t/unit/utils/test_debug.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import logging
from case import Mock, patch
diff --git a/t/unit/utils/test_div.py b/t/unit/utils/test_div.py
index f0b1a058..2a63d140 100644
--- a/t/unit/utils/test_div.py
+++ b/t/unit/utils/test_div.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pickle
from io import StringIO, BytesIO
diff --git a/t/unit/utils/test_encoding.py b/t/unit/utils/test_encoding.py
index 44c81a73..8454909a 100644
--- a/t/unit/utils/test_encoding.py
+++ b/t/unit/utils/test_encoding.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import absolute_import, unicode_literals
-
import sys
from contextlib import contextmanager
@@ -68,17 +65,17 @@ def test_default_encode():
class newbytes(bytes):
"""Mock class to simulate python-future newbytes class"""
def __repr__(self):
- return 'b' + super(newbytes, self).__repr__()
+ return 'b' + super().__repr__()
def __str__(self):
- return 'b' + "'{0}'".format(super(newbytes, self).__str__())
+ return 'b' + f"'{super().__str__()}'"
class newstr(string):
"""Mock class to simulate python-future newstr class"""
def encode(self, encoding=None, errors=None):
- return newbytes(super(newstr, self).encode(encoding, errors))
+ return newbytes(super().encode(encoding, errors))
class test_safe_str:
@@ -117,7 +114,7 @@ class test_safe_str:
def test_when_unrepresentable(self):
- class UnrepresentableObject(object):
+ class UnrepresentableObject:
def __repr__(self):
raise KeyError('foo')
diff --git a/t/unit/utils/test_functional.py b/t/unit/utils/test_functional.py
index b5ec03af..d2a4d817 100644
--- a/t/unit/utils/test_functional.py
+++ b/t/unit/utils/test_functional.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pickle
import pytest
@@ -263,7 +261,7 @@ class test_retry_over_time:
def test_retry_always(self):
Predicate = self.Predicate
- class Fun(object):
+ class Fun:
def __init__(self):
self.calls = 0
diff --git a/t/unit/utils/test_imports.py b/t/unit/utils/test_imports.py
index 20b9a2f8..79f66dc9 100644
--- a/t/unit/utils/test_imports.py
+++ b/t/unit/utils/test_imports.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
diff --git a/t/unit/utils/test_json.py b/t/unit/utils/test_json.py
index ae7b374d..ef559a72 100644
--- a/t/unit/utils/test_json.py
+++ b/t/unit/utils/test_json.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
import pytz
@@ -14,7 +12,7 @@ from kombu.utils.encoding import str_to_bytes
from kombu.utils.json import _DecodeError, dumps, loads
-class Custom(object):
+class Custom:
def __init__(self, data):
self.data = data
@@ -37,7 +35,7 @@ class test_JSONEncoder:
))
assert serialized == {
'datetime': now.isoformat(),
- 'tz': '{0}Z'.format(now_utc.isoformat().split('+', 1)[0]),
+ 'tz': '{}Z'.format(now_utc.isoformat().split('+', 1)[0]),
'time': now.time().isoformat(),
'date': stripped.isoformat(),
}
diff --git a/t/unit/utils/test_objects.py b/t/unit/utils/test_objects.py
index 8b13a405..a1ad2000 100644
--- a/t/unit/utils/test_objects.py
+++ b/t/unit/utils/test_objects.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.utils.objects import cached_property
@@ -7,7 +5,7 @@ class test_cached_property:
def test_deleting(self):
- class X(object):
+ class X:
xx = False
@cached_property
@@ -27,7 +25,7 @@ class test_cached_property:
def test_when_access_from_class(self):
- class X(object):
+ class X:
xx = None
@cached_property
diff --git a/t/unit/utils/test_scheduling.py b/t/unit/utils/test_scheduling.py
index 79216b56..52186935 100644
--- a/t/unit/utils/test_scheduling.py
+++ b/t/unit/utils/test_scheduling.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from case import Mock
diff --git a/t/unit/utils/test_time.py b/t/unit/utils/test_time.py
index 4f6ddc0b..660ae8ec 100644
--- a/t/unit/utils/test_time.py
+++ b/t/unit/utils/test_time.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from kombu.utils.time import maybe_s_to_ms
diff --git a/t/unit/utils/test_url.py b/t/unit/utils/test_url.py
index a8de493e..18588bca 100644
--- a/t/unit/utils/test_url.py
+++ b/t/unit/utils/test_url.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
try:
from urllib.parse import urlencode
except ImportError:
diff --git a/t/unit/utils/test_utils.py b/t/unit/utils/test_utils.py
index f4668b83..d118d46e 100644
--- a/t/unit/utils/test_utils.py
+++ b/t/unit/utils/test_utils.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
import pytest
from kombu import version_info_t
diff --git a/t/unit/utils/test_uuid.py b/t/unit/utils/test_uuid.py
index f6b32c28..05d89125 100644
--- a/t/unit/utils/test_uuid.py
+++ b/t/unit/utils/test_uuid.py
@@ -1,5 +1,3 @@
-from __future__ import absolute_import, unicode_literals
-
from kombu.utils.uuid import uuid