]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
New features from python 2.7
authorКатаев Денис <bteamko@gmail.com>
Fri, 17 Mar 2017 18:19:21 +0000 (14:19 -0400)
committerMike Bayer <mike_mp@zzzcomputing.com>
Fri, 17 Mar 2017 18:19:21 +0000 (14:19 -0400)
After bump minimum supported version to 2.7 (1da9d3752160430c91534a8868ceb8c5ad1451d4), we can use new syntax.

Change-Id: Ib064c75a00562e641d132f9c57e5e69744200e05
Pull-request: https://github.com/zzzeek/sqlalchemy/pull/347

23 files changed:
lib/sqlalchemy/dialects/mysql/pyodbc.py
lib/sqlalchemy/dialects/mysql/zxjdbc.py
lib/sqlalchemy/dialects/oracle/base.py
lib/sqlalchemy/engine/default.py
lib/sqlalchemy/engine/url.py
lib/sqlalchemy/ext/automap.py
lib/sqlalchemy/ext/mutable.py
lib/sqlalchemy/orm/mapper.py
lib/sqlalchemy/orm/persistence.py
lib/sqlalchemy/orm/relationships.py
lib/sqlalchemy/sql/compiler.py
lib/sqlalchemy/sql/dml.py
lib/sqlalchemy/sql/operators.py
lib/sqlalchemy/sql/schema.py
lib/sqlalchemy/sql/visitors.py
lib/sqlalchemy/testing/assertions.py
lib/sqlalchemy/testing/provision.py
lib/sqlalchemy/testing/schema.py
lib/sqlalchemy/testing/suite/test_reflection.py
lib/sqlalchemy/testing/suite/test_types.py
lib/sqlalchemy/testing/util.py
lib/sqlalchemy/util/_collections.py
lib/sqlalchemy/util/langhelpers.py

index 2ec6edf5c482212dcf729f5882aa19297e76be40..96a25d639d82409b06f9bfcbc8982b1683a1f6c2 100644 (file)
@@ -59,7 +59,7 @@ class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect):
         # If it's decided that issuing that sort of SQL leaves you SOL, then
         # this can prefer the driver value.
         rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'")
-        opts = dict([(row[0], row[1]) for row in self._compat_fetchall(rs)])
+        opts = {row[0]: row[1] for row in self._compat_fetchall(rs)}
         for key in ('character_set_connection', 'character_set'):
             if opts.get(key, None):
                 return opts[key]
index 9c92be4e6b466ce3ddfbacbce9d48e489c002457..dfbb5df43108b57d3b1a0fb492bf6334f2981961 100644 (file)
@@ -82,7 +82,7 @@ class MySQLDialect_zxjdbc(ZxJDBCConnector, MySQLDialect):
         # If it's decided that issuing that sort of SQL leaves you SOL, then
         # this can prefer the driver value.
         rs = connection.execute("SHOW VARIABLES LIKE 'character_set%%'")
-        opts = dict((row[0], row[1]) for row in self._compat_fetchall(rs))
+        opts = {row[0]: row[1] for row in self._compat_fetchall(rs)}
         for key in ('character_set_connection', 'character_set'):
             if opts.get(key, None):
                 return opts[key]
index b15affaf44b934d1553dc2e8fd5b91500c172581..06565a1c051100cbf24b40f4e0187f23dac0d4e8 100644 (file)
@@ -925,9 +925,9 @@ class OracleDDLCompiler(compiler.DDLCompiler):
 
 class OracleIdentifierPreparer(compiler.IdentifierPreparer):
 
-    reserved_words = set([x.lower() for x in RESERVED_WORDS])
-    illegal_initial_characters = set(
-        (str(dig) for dig in range(0, 10))).union(["_", "$"])
+    reserved_words = {x.lower() for x in RESERVED_WORDS}
+    illegal_initial_characters = {str(dig) for dig in range(0, 10)} \
+        .union(["_", "$"])
 
     def _bindparam_requires_quotes(self, value):
         """Return True if the given identifier requires quoting."""
@@ -1424,7 +1424,7 @@ class OracleDialect(default.DefaultDialect):
         oracle_sys_col = re.compile(r'SYS_NC\d+\$', re.IGNORECASE)
 
         def upper_name_set(names):
-            return set([i.upper() for i in names])
+            return {i.upper() for i in names}
 
         pk_names = upper_name_set(pkeys)
 
index 73cb7eeecac543beac77afb0be34b2571d872e46..dc2bd5f9762cf4e7c9565f801ec8be3738d867a7 100644 (file)
@@ -338,12 +338,12 @@ class DefaultDialect(interfaces.Dialect):
         if additional_tests:
             tests += additional_tests
 
-        results = set([check_unicode(test) for test in tests])
+        results = {check_unicode(test) for test in tests}
 
         if results.issuperset([True, False]):
             return "conditional"
         else:
-            return results == set([True])
+            return results == {True}
 
     def _check_unicode_description(self, connection):
         # all DBAPIs on Py2K return cursor.description as encoded,
@@ -694,7 +694,7 @@ class DefaultExecutionContext(interfaces.ExecutionContext):
                 self.parameters = parameters
             else:
                 self.parameters = [
-                    dict((dialect._encoder(k)[0], d[k]) for k in d)
+                    {dialect._encoder(k)[0]: d[k] for k in d}
                     for d in parameters
                 ] or [{}]
         else:
index 1c16584f124c4db867c4605e347c176140d51761..1ca5983fd528ab97fadcdc1b4be8c451cd4a9ee2 100644 (file)
@@ -222,7 +222,7 @@ def _parse_rfc1738_args(name):
             query = (
                 len(tokens) > 1 and dict(util.parse_qsl(tokens[1]))) or None
             if util.py2k and query is not None:
-                query = dict((k.encode('ascii'), query[k]) for k in query)
+                query = {k.encode('ascii'): query[k] for k in query}
         else:
             query = None
         components['query'] = query
index 219bfe124d25fc31cc78d87072e1b7fb05ff190a..14599fe5e559a36c275ccea56e878ebf0067e22c 100644 (file)
@@ -906,7 +906,7 @@ def _relationships_for_fks(automap_base, map_config, table_to_map_config,
             )
 
             o2m_kws = {}
-            nullable = False not in set([fk.parent.nullable for fk in fks])
+            nullable = False not in {fk.parent.nullable for fk in fks}
             if not nullable:
                 o2m_kws['cascade'] = "all, delete-orphan"
 
index 3361c447501346dcb42bf7bbb76c9c93cd84c70e..79459b39cbf5d8b7b1c329f4086296aff9c35f55 100644 (file)
@@ -421,7 +421,7 @@ class MutableBase(object):
         .. versionadded:: 1.0.5
 
         """
-        return set([attribute.key])
+        return {attribute.key}
 
     @classmethod
     def _listen_on_attribute(cls, attribute, coerce, parent_cls):
@@ -605,7 +605,7 @@ class MutableComposite(MutableBase):
 
     @classmethod
     def _get_listen_keys(cls, attribute):
-        return set([attribute.key]).union(attribute.property._attribute_keys)
+        return {attribute.key}.union(attribute.property._attribute_keys)
 
     def changed(self):
         """Subclasses should call this method whenever change events occur."""
index 962486d581b34cab9106a46f1d84e82f45dbf158..27456c35b8eb2062f4a1128aee6065dd17d8435e 100644 (file)
@@ -2312,9 +2312,9 @@ class Mapper(InspectionAttr):
 
         {
             tablea.col1:
-                set([tableb.col1, tablec.col1]),
+                {tableb.col1, tablec.col1},
             tablea.col2:
-                set([tabled.col2])
+                {tabled.col2}
         }
 
         """
@@ -2555,7 +2555,7 @@ class Mapper(InspectionAttr):
 
     @_memoized_configured_property
     def _primary_key_propkeys(self):
-        return set([prop.key for prop in self._all_pk_props])
+        return {prop.key for prop in self._all_pk_props}
 
     def _get_state_attr_by_column(
             self, state, dict_, column,
index ad268c127330e27015df2702875668ca4378449c..8e91dd6c7cbcc61cc79b8df29ec262c899fdbc6e 100644 (file)
@@ -86,7 +86,7 @@ def _bulk_update(mapper, mappings, session_transaction,
 
     search_keys = mapper._primary_key_propkeys
     if mapper._version_id_prop:
-        search_keys = set([mapper._version_id_prop.key]).union(search_keys)
+        search_keys = {mapper._version_id_prop.key}.union(search_keys)
 
     def _changed_dict(mapper, state):
         return dict(
index dacb68b453764de62d549355bf26001190468d66..3b83f10cdccb1b0d2d4a4debde38adc5024d5405 100644 (file)
@@ -2731,7 +2731,7 @@ class JoinCondition(object):
                 self._gather_columns_with_annotation(
                     self.secondaryjoin, annotation)
             )
-        return set([x._deannotate() for x in s])
+        return {x._deannotate() for x in s}
 
     def _gather_columns_with_annotation(self, clause, *annotation):
         annotation = set(annotation)
@@ -2857,7 +2857,7 @@ class JoinCondition(object):
                     secondaryjoin, {}, col_to_bind)
             lazywhere = sql.and_(lazywhere, secondaryjoin)
 
-        bind_to_col = dict((binds[col].key, col) for col in binds)
+        bind_to_col = {binds[col].key: col for col in binds}
 
         return lazywhere, bind_to_col, equated_columns
 
index e3bef8f8200f7ed50b4d1448f761033088edd458..4415028988d081def37366b79d3142a167674642 100644 (file)
@@ -50,7 +50,7 @@ RESERVED_WORDS = set([
     'using', 'verbose', 'when', 'where'])
 
 LEGAL_CHARACTERS = re.compile(r'^[A-Z0-9_$]+$', re.I)
-ILLEGAL_INITIAL_CHARACTERS = set([str(x) for x in range(0, 10)]).union(['$'])
+ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(['$'])
 
 BIND_PARAMS = re.compile(r'(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])', re.UNICODE)
 BIND_PARAMS_ESC = re.compile(r'\x5c(:[\w\$]*)(?![:\w\$])', re.UNICODE)
@@ -2113,8 +2113,8 @@ class SQLCompiler(Compiled):
         toplevel = not self.stack
 
         self.stack.append(
-            {'correlate_froms': set([update_stmt.table]),
-             "asfrom_froms": set([update_stmt.table]),
+            {'correlate_froms': {update_stmt.table},
+             "asfrom_froms": {update_stmt.table},
              "selectable": update_stmt})
 
         extra_froms = update_stmt._extra_froms
@@ -2193,8 +2193,8 @@ class SQLCompiler(Compiled):
     def visit_delete(self, delete_stmt, asfrom=False, **kw):
         toplevel = not self.stack
 
-        self.stack.append({'correlate_froms': set([delete_stmt.table]),
-                           "asfrom_froms": set([delete_stmt.table]),
+        self.stack.append({'correlate_froms': {delete_stmt.table},
+                           "asfrom_froms": {delete_stmt.table},
                            "selectable": delete_stmt})
 
         crud._setup_crud_params(self, delete_stmt, crud.ISDELETE, **kw)
index 767e91350445dff8947a4f2a2fd12994f25c7bcb..958e9bfb16074138a5785e78d8d29e215f5439dd 100644 (file)
@@ -582,7 +582,7 @@ class Insert(ValuesBase):
 
         self.parameters, self._has_multi_parameters = \
             self._process_colparams(
-                dict((_column_as_key(n), Null()) for n in names))
+                {_column_as_key(n): Null() for n in names})
 
         self.select_names = names
         self.inline = True
@@ -771,7 +771,7 @@ class Update(ValuesBase):
         # TODO: this could be made memoized
         # if the memoization is reset on each generative call.
         froms = []
-        seen = set([self.table])
+        seen = {self.table}
 
         if self._whereclause is not None:
             for item in _from_objects(self._whereclause):
index 01bee62cfc669628ccaf3efe3abe32965feb56ec..8f697b27eb71ade52826a7da163f94b8ead059ab 100644 (file)
@@ -1013,9 +1013,9 @@ def json_path_getitem_op(a, b):
     raise NotImplementedError()
 
 
-_commutative = set([eq, ne, add, mul])
+_commutative = {eq, ne, add, mul}
 
-_comparison = set([eq, ne, lt, gt, ge, le, between_op, like_op])
+_comparison = {eq, ne, lt, gt, ge, le, between_op, like_op}
 
 
 def is_comparison(op):
index accc1fe0d58d02aed51208123d36948c01d7e7de..46721fe83cb4d8c249aec9a969a3bccd5466d45e 100644 (file)
@@ -2603,7 +2603,7 @@ class ColumnCollectionMixin(object):
 
         columns = cols_w_table
 
-        tables = set([c.table for c in columns])
+        tables = {c.table for c in columns}
         if len(tables) == 1:
             self._set_parent_with_dispatch(tables.pop())
         elif len(tables) > 1 and not self._allow_multiple_tables:
index 7f09518246b9c9e4b30a4f4157850bf684ade2f5..99ceceed123079a2071ffaf239b45772d44aa9c9 100644 (file)
@@ -306,7 +306,7 @@ def replacement_traverse(obj, opts, replace):
     replacement by a given replacement function."""
 
     cloned = {}
-    stop_on = set([id(x) for x in opts.get('stop_on', [])])
+    stop_on = {id(x) for x in opts.get('stop_on', [])}
 
     def clone(elem, **kw):
         if id(elem) in stop_on or \
index 44551bd863c61847534f240e690ce73544d99e48..c8525f2f6c0c4602162aec81b3511b0f5e2bfb40 100644 (file)
@@ -384,8 +384,8 @@ class ComparesTables(object):
                 eq_(c.type.length, reflected_c.type.length)
 
             eq_(
-                set([f.column.name for f in c.foreign_keys]),
-                set([f.column.name for f in reflected_c.foreign_keys])
+                {f.column.name for f in c.foreign_keys},
+                {f.column.name for f in reflected_c.foreign_keys}
             )
             if c.server_default:
                 assert isinstance(reflected_c.server_default,
@@ -440,7 +440,7 @@ class AssertsExecutionResults(object):
                 return id(self)
 
         found = util.IdentitySet(result)
-        expected = set([immutabledict(e) for e in expected])
+        expected = {immutabledict(e) for e in expected}
 
         for wrong in util.itertools_filterfalse(lambda o:
                                                 isinstance(o, cls), found):
index 7e445446563643e2a786d2fd7d217c89864ea2a9..83b6115fea8476f6b0895127e4fa7a92f1c03c3e 100644 (file)
@@ -288,7 +288,7 @@ def reap_oracle_dbs(eng, idents_file):
             "select u.username from all_users u where username "
             "like 'TEST_%' and not exists (select username "
             "from v$session where username=u.username)")
-        all_names = set([username.lower() for (username, ) in to_reap])
+        all_names = {username.lower() for (username, ) in to_reap}
         to_drop = set()
         for name in all_names:
             if name.endswith("_ts1") or name.endswith("_ts2"):
index 018a291d9f273d0fe1d4faf8822fc4d4ce65d734..f40654a2a326978cce545798c2b302662129919d 100644 (file)
@@ -17,8 +17,7 @@ table_options = {}
 def Table(*args, **kw):
     """A schema.Table wrapper/hook for dialect-specific tweaks."""
 
-    test_opts = dict([(k, kw.pop(k)) for k in list(kw)
-                      if k.startswith('test_')])
+    test_opts = {k: kw.pop(k) for k in list(kw) if k.startswith('test_')}
 
     kw.update(table_options)
 
@@ -64,8 +63,7 @@ def Table(*args, **kw):
 def Column(*args, **kw):
     """A schema.Column wrapper/hook for dialect-specific tweaks."""
 
-    test_opts = dict([(k, kw.pop(k)) for k in list(kw)
-                      if k.startswith('test_')])
+    test_opts = {k: kw.pop(k) for k in list(kw) if k.startswith('test_')}
 
     if not config.requirements.foreign_key_ddl.enabled_for_config(config):
         args = [arg for arg in args if not isinstance(arg, schema.ForeignKey)]
index a761c0882a42c60549a3569d51855dbf1d3d6fa2..f47b34bf45a2622f59ba71b3cee0265b3e2cf55c 100644 (file)
@@ -746,7 +746,7 @@ class ComponentReflectionTest(fixtures.TablesTest):
             ('dingalings', 'dingaling_id'),
         ]:
             cols = insp.get_columns(tname)
-            id_ = dict((c['name'], c) for c in cols)[cname]
+            id_ = {c['name']: c for c in cols}[cname]
             assert id_.get('autoincrement', True)
 
 
index dbbe031118d252042e22dd5d7f8a8b983c69a805..ee757e1cafc948ec026610333f086f7e26c33fd8 100644 (file)
@@ -340,7 +340,7 @@ class NumericTest(_LiteralRoundTripFixture, fixtures.TestBase):
         t.create()
         t.insert().execute([{'x': x} for x in input_])
 
-        result = set([row[0] for row in t.select().execute()])
+        result = {row[0] for row in t.select().execute()}
         output = set(output)
         if filter_:
             result = set(filter_(x) for x in result)
index 8f91f31ed38dd47dcc1e8ef05071b1f763c76c67..a37637ac02974dd79828cd0d32948a6697e455b4 100644 (file)
@@ -173,7 +173,7 @@ def rowset(results):
     Useful for asserting the results of an unordered query.
     """
 
-    return set([tuple(row) for row in results])
+    return {tuple(row) for row in results}
 
 
 def fail(msg):
index e3e1d71dcf64817239f419633fb8c9812eb6c1ff..bdd40fc794abb077a8f07b835feacc5bcf1130c1 100644 (file)
@@ -107,7 +107,7 @@ class KeyedTuple(AbstractKeyedTuple):
         .. versionadded:: 0.8
 
         """
-        return dict((key, self.__dict__[key]) for key in self.keys())
+        return {key: self.__dict__[key] for key in self.keys()}
 
 
 class _LW(AbstractKeyedTuple):
index 68c0f885b58c4c1659d90eb2f29687b19d9488b3..41fed882dca6680344217c6c1d39c1be24bf691d 100644 (file)
@@ -567,7 +567,7 @@ def class_hierarchy(cls):
         if isinstance(cls, types.ClassType):
             return list()
 
-    hier = set([cls])
+    hier = {cls}
     process = list(cls.__mro__)
     while process:
         c = process.pop()