Browse Source

Prefer dict literal syntax over dict() (#4217)

Mads Jensen 7 years ago
parent
commit
39d86e7dbe

+ 1 - 0
CONTRIBUTORS.txt

@@ -247,4 +247,5 @@ David Davis, 2017/08/11
 Martial Pageau, 2017/08/16
 Sammie S. Taunton, 2017/08/17
 Kxrr, 2017/08/18
+Mads Jensen, 2017/08/20
 Markus Kaiserswerth, 2017/08/30

+ 2 - 2
celery/app/defaults.py

@@ -56,8 +56,8 @@ class Option(object):
     deprecate_by = None
     remove_by = None
     old = set()
-    typemap = dict(string=str, int=int, float=float, any=lambda v: v,
-                   bool=strtobool, dict=dict, tuple=tuple)
+    typemap = {'string': str, 'int': int, 'float': float, 'any': lambda v: v,
+               'bool': strtobool, 'dict': dict, 'tuple': tuple}
 
     def __init__(self, default=None, *args, **kwargs):
         self.default = default

+ 4 - 4
celery/app/utils.py

@@ -278,10 +278,10 @@ class AppPickler(object):
     def build_standard_kwargs(self, main, changes, loader, backend, amqp,
                               events, log, control, accept_magic_kwargs,
                               config_source=None):
-        return dict(main=main, loader=loader, backend=backend, amqp=amqp,
-                    changes=changes, events=events, log=log, control=control,
-                    set_as_current=False,
-                    config_source=config_source)
+        return {'main': main, 'loader': loader, 'backend': backend,
+                'amqp': amqp, 'changes': changes, 'events': events,
+                'log': log, 'control': control, 'set_as_current': False,
+                'config_source': config_source}
 
     def construct(self, cls, **kwargs):
         return cls(**kwargs)

+ 3 - 3
celery/backends/cache.py

@@ -147,9 +147,9 @@ class CacheBackend(KeyValueStoreBackend):
         servers = ';'.join(self.servers)
         backend = '{0}://{1}/'.format(self.backend, servers)
         kwargs.update(
-            dict(backend=backend,
-                 expires=self.expires,
-                 options=self.options))
+            {'backend': backend,
+             'expires': self.expires,
+             'options': self.options})
         return super(CacheBackend, self).__reduce__(args, kwargs)
 
     def as_uri(self, *args, **kwargs):

+ 3 - 3
celery/backends/cassandra.py

@@ -224,7 +224,7 @@ class CassandraBackend(BaseBackend):
 
     def __reduce__(self, args=(), kwargs={}):
         kwargs.update(
-            dict(servers=self.servers,
-                 keyspace=self.keyspace,
-                 table=self.table))
+            {'servers': self.servers,
+             'keyspace': self.keyspace,
+             'table': self.table})
         return super(CassandraBackend, self).__reduce__(args, kwargs)

+ 3 - 3
celery/backends/database/__init__.py

@@ -182,7 +182,7 @@ class DatabaseBackend(BaseBackend):
 
     def __reduce__(self, args=(), kwargs={}):
         kwargs.update(
-            dict(dburi=self.url,
-                 expires=self.expires,
-                 engine_options=self.engine_options))
+            {'dburi': self.url,
+             'expires': self.expires,
+             'engine_options': self.engine_options})
         return super(DatabaseBackend, self).__reduce__(args, kwargs)

+ 21 - 21
celery/backends/dynamodb.py

@@ -126,14 +126,14 @@ class DynamoDBBackend(KeyValueStoreBackend):
     def _get_client(self, access_key_id=None, secret_access_key=None):
         """Get client connection."""
         if self._client is None:
-            client_parameters = dict(
-                region_name=self.aws_region
-            )
+            client_parameters = {
+                'region_name': self.aws_region
+            }
             if access_key_id is not None:
-                client_parameters.update(dict(
-                    aws_access_key_id=access_key_id,
-                    aws_secret_access_key=secret_access_key
-                ))
+                client_parameters.update({
+                    'aws_access_key_id': access_key_id,
+                    'aws_secret_access_key': secret_access_key
+                })
 
             if self.endpoint_url is not None:
                 client_parameters['endpoint_url'] = self.endpoint_url
@@ -147,25 +147,25 @@ class DynamoDBBackend(KeyValueStoreBackend):
 
     def _get_table_schema(self):
         """Get the boto3 structure describing the DynamoDB table schema."""
-        return dict(
-            AttributeDefinitions=[
+        return {
+            'AttributeDefinitions': [
                 {
                     'AttributeName': self._key_field.name,
                     'AttributeType': self._key_field.data_type
                 }
             ],
-            TableName=self.table_name,
-            KeySchema=[
+            'TableName': self.table_name,
+            'KeySchema': [
                 {
                     'AttributeName': self._key_field.name,
                     'KeyType': 'HASH'
                 }
             ],
-            ProvisionedThroughput={
+            'ProvisionedThroughput': {
                 'ReadCapacityUnits': self.read_capacity_units,
                 'WriteCapacityUnits': self.write_capacity_units
             }
-        )
+        }
 
     def _get_or_create_table(self):
         """Create table if not exists, otherwise return the description."""
@@ -215,20 +215,20 @@ class DynamoDBBackend(KeyValueStoreBackend):
 
     def _prepare_get_request(self, key):
         """Construct the item retrieval request parameters."""
-        return dict(
-            TableName=self.table_name,
-            Key={
+        return {
+            'TableName': self.table_name,
+            'Key': {
                 self._key_field.name: {
                     self._key_field.data_type: key
                 }
             }
-        )
+        }
 
     def _prepare_put_request(self, key, value):
         """Construct the item creation request parameters."""
-        return dict(
-            TableName=self.table_name,
-            Item={
+        return {
+            'TableName': self.table_name,
+            'Item': {
                 self._key_field.name: {
                     self._key_field.data_type: key
                 },
@@ -239,7 +239,7 @@ class DynamoDBBackend(KeyValueStoreBackend):
                     self._timestamp_field.data_type: str(time())
                 }
             }
-        )
+        }
 
     def _item_to_dict(self, raw_response):
         """Convert get_item() response to field-value pairs."""

+ 9 - 9
celery/bin/base.py

@@ -88,15 +88,15 @@ def _add_optparse_argument(parser, opt, typemap={
             opt.default = False
     parser.add_argument(
         *opt._long_opts + opt._short_opts,
-        **dictfilter(dict(
-            action=opt.action,
-            type=typemap.get(opt.type, opt.type),
-            dest=opt.dest,
-            nargs=opt.nargs,
-            choices=opt.choices,
-            help=opt.help,
-            metavar=opt.metavar,
-            default=opt.default)))
+        **dictfilter({
+            'action': opt.action,
+            'type': typemap.get(opt.type, opt.type),
+            'dest': opt.dest,
+            'nargs': opt.nargs,
+            'choices': opt.choices,
+            'help': opt.help,
+            'metavar': opt.metavar,
+            'default': opt.default}))
 
 
 def _add_compat_options(parser, options):

+ 2 - 2
celery/canvas.py

@@ -1187,8 +1187,8 @@ class chord(Signature):
                  args=(), kwargs={}, app=None, **options):
         Signature.__init__(
             self, task, args,
-            dict(kwargs=kwargs, header=_maybe_group(header, app),
-                 body=maybe_signature(body, app=app)), app=app, **options
+            {'kwargs': kwargs, 'header': _maybe_group(header, app),
+             'body': maybe_signature(body, app=app)}, app=app, **options
         )
         self.subtask_type = 'chord'
 

+ 6 - 6
celery/local.py

@@ -555,12 +555,12 @@ def recreate_module(name, compat_modules=(), by_module={}, direct={},
     )))
     if sys.version_info[0] < 3:
         _all = [s.encode() for s in _all]
-    cattrs = dict(
-        _compat_modules=compat_modules,
-        _all_by_module=by_module, _direct=direct,
-        _object_origins=origins,
-        __all__=_all,
-    )
+    cattrs = {
+        '_compat_modules': compat_modules,
+        '_all_by_module': by_module, '_direct': direct,
+        '_object_origins': origins,
+        '__all__': _all,
+    }
     new_module = create_module(name, attrs, cls_attrs=cattrs, base=base)
     new_module.__dict__.update({
         mod: get_compat_module(new_module, mod) for mod in compat_modules

+ 7 - 7
t/unit/app/test_amqp.py

@@ -135,24 +135,24 @@ class test_Queues:
         assert q['barfoo'] is q['foo']
 
     @pytest.mark.parametrize('queues_kwargs,qname,q,expected', [
-        (dict(max_priority=10),
+        ({'max_priority': 10},
          'foo', 'foo', {'x-max-priority': 10}),
-        (dict(max_priority=10),
+        ({'max_priority': 10},
          'xyz', Queue('xyz', queue_arguments={'x-max-priority': 3}),
          {'x-max-priority': 3}),
-        (dict(max_priority=10),
+        ({'max_priority': 10},
          'moo', Queue('moo', queue_arguments=None),
          {'x-max-priority': 10}),
-        (dict(ha_policy='all', max_priority=5),
+        ({'ha_policy': 'all', 'max_priority': 5},
          'bar', 'bar',
          {'x-ha-policy': 'all', 'x-max-priority': 5}),
-        (dict(ha_policy='all', max_priority=5),
+        ({'ha_policy': 'all', 'max_priority': 5},
          'xyx2', Queue('xyx2', queue_arguments={'x-max-priority': 2}),
          {'x-ha-policy': 'all', 'x-max-priority': 2}),
-        (dict(max_priority=None),
+        ({'max_priority': None},
          'foo2', 'foo2',
          None),
-        (dict(max_priority=None),
+        ({'max_priority': None},
          'xyx3', Queue('xyx3', queue_arguments={'x-max-priority': 7}),
          {'x-max-priority': 7}),
 

+ 3 - 3
t/unit/app/test_app.py

@@ -36,7 +36,7 @@ class ObjectConfig(object):
 
 
 object_config = ObjectConfig()
-dict_config = dict(FOO=10, BAR=20)
+dict_config = {'FOO': 10, 'BAR': 20}
 
 
 class ObjectConfig2(object):
@@ -537,8 +537,8 @@ class test_App:
             _task_stack.pop()
 
     def test_pickle_app(self):
-        changes = dict(THE_FOO_BAR='bars',
-                       THE_MII_MAR='jars')
+        changes = {'THE_FOO_BAR': 'bars',
+                   'THE_MII_MAR': 'jars'}
         self.app.conf.update(changes)
         saved = pickle.dumps(self.app)
         assert len(saved) < 2048

+ 14 - 15
t/unit/app/test_beat.py

@@ -41,13 +41,13 @@ class test_ScheduleEntry:
     Entry = beat.ScheduleEntry
 
     def create_entry(self, **kwargs):
-        entry = dict(
-            name='celery.unittest.add',
-            schedule=timedelta(seconds=10),
-            args=(2, 2),
-            options={'routing_key': 'cpu'},
-            app=self.app,
-        )
+        entry = {
+            'name': 'celery.unittest.add',
+            'schedule': timedelta(seconds=10),
+            'args': (2, 2),
+            'options': {'routing_key': 'cpu'},
+            'app': self.app,
+        }
         return self.Entry(**dict(entry, **kwargs))
 
     def test_next(self):
@@ -309,9 +309,8 @@ class test_Scheduler:
     def test_ticks(self):
         scheduler = mScheduler(app=self.app)
         nums = [600, 300, 650, 120, 250, 36]
-        s = dict(('test_ticks%s' % i,
-                 {'schedule': mocked_schedule(False, j)})
-                 for i, j in enumerate(nums))
+        s = {'test_ticks%s' % i: {'schedule': mocked_schedule(False, j)}
+             for i, j in enumerate(nums)}
         scheduler.update_from_dict(s)
         assert scheduler.tick() == min(nums) - 0.010
 
@@ -367,11 +366,11 @@ class test_Scheduler:
         assert scheduler._heap == [event_t(1, 5, scheduler.schedule['foo'])]
 
     def create_schedule_entry(self, schedule):
-        entry = dict(
-            name='celery.unittest.add',
-            schedule=schedule,
-            app=self.app,
-        )
+        entry = {
+            'name': 'celery.unittest.add',
+            'schedule': schedule,
+            'app': self.app,
+        }
         return beat.ScheduleEntry(**dict(entry))
 
     def test_schedule_equal_schedule_vs_schedule_success(self):

+ 1 - 1
t/unit/backends/test_amqp.py

@@ -29,7 +29,7 @@ class test_AMQPBackend:
         self.app.conf.result_cache_max = 100
 
     def create_backend(self, **opts):
-        opts = dict(dict(serializer='pickle', persistent=True), **opts)
+        opts = dict({'serializer': 'pickle', 'persistent': True}, **opts)
         return AMQPBackend(self.app, **opts)
 
     def test_destination_for(self):

+ 4 - 4
t/unit/backends/test_dynamodb.py

@@ -204,14 +204,14 @@ class test_DynamoDBBackend:
 
         assert self.backend._client.put_item.call_count == 1
         _, call_kwargs = self.backend._client.put_item.call_args
-        expected_kwargs = dict(
-            Item={
+        expected_kwargs = {
+            'Item': {
                 u'timestamp': {u'N': str(self._static_timestamp)},
                 u'id': {u'S': string(sentinel.key)},
                 u'result': {u'B': sentinel.value}
             },
-            TableName='celery'
-        )
+            'TableName': 'celery'
+        }
         assert call_kwargs['Item'] == expected_kwargs['Item']
         assert call_kwargs['TableName'] == 'celery'
 

+ 9 - 9
t/unit/backends/test_elasticsearch.py

@@ -26,7 +26,7 @@ class test_ElasticsearchBackend:
         x._server = Mock()
         x._server.get = Mock()
         # expected result
-        r = dict(found=True, _source={'result': sentinel.result})
+        r = {'found': True, '_source': {'result': sentinel.result}}
         x._server.get.return_value = r
         dict_result = x.get(sentinel.task_id)
 
@@ -86,10 +86,10 @@ class test_ElasticsearchBackend:
         x.doc_type = 'test-doc-type'
         x._server = Mock()
         x._server.index = Mock()
-        expected_result = dict(
-            _id=sentinel.task_id,
-            _source={'result': sentinel.result}
-        )
+        expected_result = {
+            '_id': sentinel.task_id,
+            '_source': {'result': sentinel.result}
+        }
         x._server.index.return_value = expected_result
 
         body = {"field1": "value1"}
@@ -111,10 +111,10 @@ class test_ElasticsearchBackend:
         x.doc_type = 'test-doc-type'
         x._server = Mock()
         x._server.index = Mock()
-        expected_result = dict(
-            _id=sentinel.task_id,
-            _source={'result': sentinel.result}
-        )
+        expected_result = {
+            '_id': sentinel.task_id,
+            '_source': {'result': sentinel.result}
+        }
         x._server.index.return_value = expected_result
 
         body = {b"field1": "value1"}

+ 1 - 1
t/unit/bin/test_base.py

@@ -21,7 +21,7 @@ class MockCommand(Command):
     mock_args = ('arg1', 'arg2', 'arg3')
 
     def parse_options(self, prog_name, arguments, command=None):
-        options = dict(foo='bar', prog_name=prog_name)
+        options = {'foo': 'bar', 'prog_name': prog_name}
         return options, self.mock_args
 
     def run(self, *args, **kwargs):

+ 3 - 3
t/unit/contrib/test_migrate.py

@@ -267,9 +267,9 @@ class test_migrate_task:
 class test_migrate_tasks:
 
     def test_migrate(self, app, name='testcelery'):
-        connection_kwargs = dict(
-            transport_options={'polling_interval': 0.01}
-        )
+        connection_kwargs = {
+            'transport_options': {'polling_interval': 0.01}
+        }
         x = Connection('memory://foo', **connection_kwargs)
         y = Connection('memory://foo', **connection_kwargs)
         # use separate state

+ 4 - 2
t/unit/tasks/test_canvas.py

@@ -563,13 +563,15 @@ class test_group(CanvasCase):
 
     def test_kwargs_apply(self):
         x = group([self.add.s(), self.add.s()])
-        res = x.apply(kwargs=dict(x=1, y=1)).get()
+        res = x.apply(kwargs={'x': 1, 'y': 1}).get()
         assert res == [2, 2]
 
     def test_kwargs_apply_async(self):
         self.app.conf.task_always_eager = True
         x = group([self.add.s(), self.add.s()])
-        res = self.helper_test_get_delay(x.apply_async(kwargs=dict(x=1, y=1)))
+        res = self.helper_test_get_delay(
+            x.apply_async(kwargs={'x': 1, 'y': 1})
+        )
         assert res == [2, 2]
 
     def test_kwargs_delay(self):

+ 3 - 3
t/unit/tasks/test_context.py

@@ -30,7 +30,7 @@ class test_Context:
 
     def test_updated_context(self):
         expected = dict(default_context)
-        changes = dict(id='unique id', args=['some', 1], wibble='wobble')
+        changes = {'id': 'unique id', 'args': ['some', 1], 'wibble': 'wobble'}
         ctx = Context()
         expected.update(changes)
         ctx.update(changes)
@@ -48,7 +48,7 @@ class test_Context:
         assert get_context_as_dict(Context()) == default_context
 
     def test_cleared_context(self):
-        changes = dict(id='unique id', args=['some', 1], wibble='wobble')
+        changes = {'id': 'unique id', 'args': ['some', 1], 'wibble': 'wobble'}
         ctx = Context()
         ctx.update(changes)
         ctx.clear()
@@ -58,7 +58,7 @@ class test_Context:
 
     def test_context_get(self):
         expected = dict(default_context)
-        changes = dict(id='unique id', args=['some', 1], wibble='wobble')
+        changes = {'id': 'unique id', 'args': ['some', 1], 'wibble': 'wobble'}
         ctx = Context()
         expected.update(changes)
         ctx.update(changes)

+ 4 - 4
t/unit/tasks/test_result.py

@@ -36,10 +36,10 @@ Doesn't matter: really!\
 
 
 def mock_task(name, state, result, traceback=None):
-    return dict(
-        id=uuid(), name=name, state=state,
-        result=result, traceback=traceback,
-    )
+    return {
+        'id': uuid(), 'name': name, 'state': state,
+        'result': result, 'traceback': traceback,
+    }
 
 
 def save_result(app, task):

+ 4 - 4
t/unit/tasks/test_tasks.py

@@ -467,7 +467,7 @@ class test_tasks(TasksCase):
 
             # With arguments.
             presult2 = self.mytask.apply_async(
-                kwargs=dict(name='George Costanza'),
+                kwargs={'name': 'George Costanza'},
             )
             self.assert_next_task_data_equal(
                 consumer, presult2, self.mytask.name, name='George Costanza',
@@ -475,14 +475,14 @@ class test_tasks(TasksCase):
 
             # send_task
             sresult = self.app.send_task(self.mytask.name,
-                                         kwargs=dict(name='Elaine M. Benes'))
+                                         kwargs={'name': 'Elaine M. Benes'})
             self.assert_next_task_data_equal(
                 consumer, sresult, self.mytask.name, name='Elaine M. Benes',
             )
 
             # With ETA.
             presult2 = self.mytask.apply_async(
-                kwargs=dict(name='George Costanza'),
+                kwargs={'name': 'George Costanza'},
                 eta=self.now() + timedelta(days=1),
                 expires=self.now() + timedelta(days=2),
             )
@@ -493,7 +493,7 @@ class test_tasks(TasksCase):
 
             # With countdown.
             presult2 = self.mytask.apply_async(
-                kwargs=dict(name='George Costanza'), countdown=10, expires=12,
+                kwargs={'name': 'George Costanza'}, countdown=10, expires=12,
             )
             self.assert_next_task_data_equal(
                 consumer, presult2, self.mytask.name,

+ 14 - 14
t/unit/worker/test_control.py

@@ -232,19 +232,19 @@ class test_ControlPanel:
 
     def test_time_limit(self):
         panel = self.create_panel(consumer=Mock())
-        r = panel.handle('time_limit', arguments=dict(
-            task_name=self.mytask.name, hard=30, soft=10))
+        r = panel.handle('time_limit', arguments={
+            'task_name': self.mytask.name, 'hard': 30, 'soft': 10})
         assert self.mytask.time_limit == 30
         assert self.mytask.soft_time_limit == 10
         assert 'ok' in r
-        r = panel.handle('time_limit', arguments=dict(
-            task_name=self.mytask.name, hard=None, soft=None))
+        r = panel.handle('time_limit', arguments={
+            'task_name': self.mytask.name, 'hard': None, 'soft': None})
         assert self.mytask.time_limit is None
         assert self.mytask.soft_time_limit is None
         assert 'ok' in r
 
-        r = panel.handle('time_limit', arguments=dict(
-            task_name='248e8afya9s8dh921eh928', hard=30))
+        r = panel.handle('time_limit', arguments={
+            'task_name': '248e8afya9s8dh921eh928', 'hard': 30})
         assert 'error' in r
 
     def test_active_queues(self):
@@ -416,8 +416,8 @@ class test_ControlPanel:
             worker_state.reserved_requests.clear()
 
     def test_rate_limit_invalid_rate_limit_string(self):
-        e = self.panel.handle('rate_limit', arguments=dict(
-            task_name='tasks.add', rate_limit='x1240301#%!'))
+        e = self.panel.handle('rate_limit', arguments={
+            'task_name': 'tasks.add', 'rate_limit': 'x1240301#%!'})
         assert 'Invalid rate limit string' in e.get('error')
 
     def test_rate_limit(self):
@@ -432,15 +432,15 @@ class test_ControlPanel:
         panel = self.create_panel(app=self.app, consumer=consumer)
 
         task = self.app.tasks[self.mytask.name]
-        panel.handle('rate_limit', arguments=dict(task_name=task.name,
-                                                  rate_limit='100/m'))
+        panel.handle('rate_limit', arguments={'task_name': task.name,
+                                              'rate_limit': '100/m'})
         assert task.rate_limit == '100/m'
         assert consumer.reset
         consumer.reset = False
-        panel.handle('rate_limit', arguments=dict(
-            task_name=task.name,
-            rate_limit=0,
-        ))
+        panel.handle('rate_limit', arguments={
+            'task_name': task.name,
+            'rate_limit': 0,
+        })
         assert task.rate_limit == 0
         assert consumer.reset