diff options
author | Mike Bayer <mike_mp@zzzcomputing.com> | 2019-01-05 13:00:20 -0500 |
---|---|---|
committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2019-01-05 16:38:21 -0500 |
commit | 42924cf282e8f748d2fdbb9338353cfcaaff4df2 (patch) | |
tree | d4bcf66e47ccfc4cccd46f1d756703afe55c57cb | |
parent | d0bd8077a361fdaab3733e9e3cce39e541f32e5b (diff) | |
download | sqlalchemy-42924cf282e8f748d2fdbb9338353cfcaaff4df2.tar.gz |
flake8 refactor - ext
A full rewrite of all imports and pep8 formatting using zimports, black,
commits are broken into sections.
Directories included in this commit:
lib/sqlalchemy/ext/
Change-Id: I3dd7aed3f42675e9ada64446ffd2758db7c3bc93
(cherry picked from commit 0716a292e03040ad4f96b890691b9e2c888ec11d)
-rw-r--r-- | lib/sqlalchemy/ext/associationproxy.py | 20 | ||||
-rw-r--r-- | lib/sqlalchemy/ext/baked.py | 11 | ||||
-rw-r--r-- | lib/sqlalchemy/ext/declarative/api.py | 9 | ||||
-rw-r--r-- | lib/sqlalchemy/ext/declarative/base.py | 11 | ||||
-rw-r--r-- | lib/sqlalchemy/ext/hybrid.py | 138 | ||||
-rw-r--r-- | lib/sqlalchemy/ext/mutable.py | 4 | ||||
-rw-r--r-- | lib/sqlalchemy/ext/serializer.py | 20 | ||||
-rw-r--r-- | lib/sqlalchemy/orm/interfaces.py | 1 |
8 files changed, 112 insertions, 102 deletions
diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py index 901008fa8..fd0884292 100644 --- a/lib/sqlalchemy/ext/associationproxy.py +++ b/lib/sqlalchemy/ext/associationproxy.py @@ -646,11 +646,11 @@ class _AssociationList(_AssociationCollection): def _create(self, value): return self.creator(value) - def _get(self, object): - return self.getter(object) + def _get(self, object_): + return self.getter(object_) - def _set(self, object, value): - return self.setter(object, value) + def _set(self, object_, value): + return self.setter(object_, value) def __getitem__(self, index): if not isinstance(index, slice): @@ -856,11 +856,11 @@ class _AssociationDict(_AssociationCollection): def _create(self, key, value): return self.creator(key, value) - def _get(self, object): - return self.getter(object) + def _get(self, object_): + return self.getter(object_) - def _set(self, object, key, value): - return self.setter(object, key, value) + def _set(self, object_, key, value): + return self.setter(object_, key, value) def __getitem__(self, key): return self._get(self.col[key]) @@ -1013,8 +1013,8 @@ class _AssociationSet(_AssociationCollection): def _create(self, value): return self.creator(value) - def _get(self, object): - return self.getter(object) + def _get(self, object_): + return self.getter(object_) def __len__(self): return len(self.col) diff --git a/lib/sqlalchemy/ext/baked.py b/lib/sqlalchemy/ext/baked.py index 0919c80fe..a4cc30044 100644 --- a/lib/sqlalchemy/ext/baked.py +++ b/lib/sqlalchemy/ext/baked.py @@ -21,6 +21,17 @@ from .. import util from ..orm import exc as orm_exc from ..orm import strategy_options from ..orm.query import Query +from ..orm.session import Session +from ..sql import func +from ..sql import literal_column +from ..sql import util as sql_util + + +from .. import exc as sa_exc +from .. import util +from ..orm import exc as orm_exc +from ..orm import strategy_options +from ..orm.query import Query from ..sql import func from ..sql import literal_column from ..sql import util as sql_util diff --git a/lib/sqlalchemy/ext/declarative/api.py b/lib/sqlalchemy/ext/declarative/api.py index 2f41db126..5dcf543dc 100644 --- a/lib/sqlalchemy/ext/declarative/api.py +++ b/lib/sqlalchemy/ext/declarative/api.py @@ -75,6 +75,7 @@ class DeclarativeMeta(type): _add_attribute(cls, key, value) + def synonym_for(name, map_column=False): """Decorator that produces an :func:`.orm.synonym` attribute in conjunction with a Python descriptor. @@ -253,7 +254,8 @@ class declared_attr(interfaces._MappedAttribute, property): @declared_attr.cascading def id(cls): if has_inherited_table(cls): - return Column(ForeignKey('myclass.id'), primary_key=True) + return Column( + ForeignKey('myclass.id'), primary_key=True) else: return Column(Integer, primary_key=True) @@ -357,8 +359,9 @@ def declarative_base( compatible callable to use as the meta type of the generated declarative base class. - .. versionchanged:: 1.1 if :paramref:`.declarative_base.cls` is a single class (rather - than a tuple), the constructed base class will inherit its docstring. + .. versionchanged:: 1.1 if :paramref:`.declarative_base.cls` is a + single class (rather than a tuple), the constructed base class will + inherit its docstring. .. seealso:: diff --git a/lib/sqlalchemy/ext/declarative/base.py b/lib/sqlalchemy/ext/declarative/base.py index 9fee49c0d..2198064ce 100644 --- a/lib/sqlalchemy/ext/declarative/base.py +++ b/lib/sqlalchemy/ext/declarative/base.py @@ -235,9 +235,9 @@ class _MapperConfig(object): # make a copy of it so a class-level dictionary # is not overwritten when we update column-based # arguments. - mapper_args_fn = lambda: dict( - cls.__mapper_args__ - ) # noqa + def mapper_args_fn(): + return dict(cls.__mapper_args__) + elif name == "__tablename__": check_decl = _check_declared_props_nocascade( obj, name, cls @@ -290,8 +290,9 @@ class _MapperConfig(object): # defined attribute here to allow a clean # override, if there's another # subclass below then it still tries to use - # this. not sure if there is enough information - # here to add this as a feature later on. + # this. not sure if there is enough + # information here to add this as a feature + # later on. util.warn( "Attribute '%s' on class %s cannot be " "processed due to " diff --git a/lib/sqlalchemy/ext/hybrid.py b/lib/sqlalchemy/ext/hybrid.py index 8fca0b29c..877b1b282 100644 --- a/lib/sqlalchemy/ext/hybrid.py +++ b/lib/sqlalchemy/ext/hybrid.py @@ -16,8 +16,8 @@ dependencies on the rest of SQLAlchemy. It can, in theory, work with any descriptor-based expression system. Consider a mapping ``Interval``, representing integer ``start`` and ``end`` -values. We can define higher level functions on mapped classes that produce -SQL expressions at the class level, and Python expression evaluation at the +values. We can define higher level functions on mapped classes that produce SQL +expressions at the class level, and Python expression evaluation at the instance level. Below, each function decorated with :class:`.hybrid_method` or :class:`.hybrid_property` may receive ``self`` as an instance of the class, or as the class itself:: @@ -410,7 +410,8 @@ idiosyncratic behavior on the SQL side. .. note:: The :meth:`.hybrid_property.comparator` decorator introduced in this section **replaces** the use of the - :meth:`.hybrid_property.expression` decorator. They cannot be used together. + :meth:`.hybrid_property.expression` decorator. + They cannot be used together. The example class below allows case-insensitive comparisons on the attribute named ``word_insensitive``:: @@ -496,13 +497,12 @@ Above, the ``FirstNameLastName`` class refers to the hybrid from ``FirstNameOnly.name`` to repurpose its getter and setter for the subclass. When overriding :meth:`.hybrid_property.expression` and -:meth:`.hybrid_property.comparator` alone as the first reference -to the superclass, these names conflict -with the same-named accessors on the class-level :class:`.QueryableAttribute` -object returned at the class level. To override these methods when -referring directly to the parent class descriptor, add -the special qualifier :attr:`.hybrid_property.overrides`, which will -de-reference the instrumented attribute back to the hybrid object:: +:meth:`.hybrid_property.comparator` alone as the first reference to the +superclass, these names conflict with the same-named accessors on the class- +level :class:`.QueryableAttribute` object returned at the class level. To +override these methods when referring directly to the parent class descriptor, +add the special qualifier :attr:`.hybrid_property.overrides`, which will de- +reference the instrumented attribute back to the hybrid object:: class FirstNameLastName(FirstNameOnly): # ... @@ -520,19 +520,18 @@ de-reference the instrumented attribute back to the hybrid object:: Hybrid Value Objects -------------------- -Note in our previous example, if we were to compare the -``word_insensitive`` attribute of a ``SearchWord`` instance to a plain -Python string, the plain Python string would not be coerced to lower -case - the ``CaseInsensitiveComparator`` we built, being returned by +Note in our previous example, if we were to compare the ``word_insensitive`` +attribute of a ``SearchWord`` instance to a plain Python string, the plain +Python string would not be coerced to lower case - the +``CaseInsensitiveComparator`` we built, being returned by ``@word_insensitive.comparator``, only applies to the SQL side. -A more comprehensive form of the custom comparator is to construct a -*Hybrid Value Object*. This technique applies the target value or -expression to a value object which is then returned by the accessor in -all cases. The value object allows control of all operations upon -the value as well as how compared values are treated, both on the SQL -expression side as well as the Python value side. Replacing the -previous ``CaseInsensitiveComparator`` class with a new +A more comprehensive form of the custom comparator is to construct a *Hybrid +Value Object*. This technique applies the target value or expression to a value +object which is then returned by the accessor in all cases. The value object +allows control of all operations upon the value as well as how compared values +are treated, both on the SQL expression side as well as the Python value side. +Replacing the previous ``CaseInsensitiveComparator`` class with a new ``CaseInsensitiveWord`` class:: class CaseInsensitiveWord(Comparator): @@ -560,13 +559,12 @@ previous ``CaseInsensitiveComparator`` class with a new key = 'word' "Label to apply to Query tuple results" -Above, the ``CaseInsensitiveWord`` object represents ``self.word``, -which may be a SQL function, or may be a Python native. By -overriding ``operate()`` and ``__clause_element__()`` to work in terms -of ``self.word``, all comparison operations will work against the -"converted" form of ``word``, whether it be SQL side or Python side. -Our ``SearchWord`` class can now deliver the ``CaseInsensitiveWord`` -object unconditionally from a single hybrid call:: +Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may +be a SQL function, or may be a Python native. By overriding ``operate()`` and +``__clause_element__()`` to work in terms of ``self.word``, all comparison +operations will work against the "converted" form of ``word``, whether it be +SQL side or Python side. Our ``SearchWord`` class can now deliver the +``CaseInsensitiveWord`` object unconditionally from a single hybrid call:: class SearchWord(Base): __tablename__ = 'searchword' @@ -577,10 +575,9 @@ object unconditionally from a single hybrid call:: def word_insensitive(self): return CaseInsensitiveWord(self.word) -The ``word_insensitive`` attribute now has case-insensitive comparison -behavior universally, including SQL expression vs. Python expression -(note the Python value is converted to lower case on the Python side -here):: +The ``word_insensitive`` attribute now has case-insensitive comparison behavior +universally, including SQL expression vs. Python expression (note the Python +value is converted to lower case on the Python side here):: >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks") SELECT searchword.id AS searchword_id, searchword.word AS searchword_word @@ -612,9 +609,9 @@ Python only expression:: >>> print ws1.word_insensitive someword -The Hybrid Value pattern is very useful for any kind of value that may -have multiple representations, such as timestamps, time deltas, units -of measurement, currencies and encrypted passwords. +The Hybrid Value pattern is very useful for any kind of value that may have +multiple representations, such as timestamps, time deltas, units of +measurement, currencies and encrypted passwords. .. seealso:: @@ -631,17 +628,17 @@ of measurement, currencies and encrypted passwords. Building Transformers ---------------------- -A *transformer* is an object which can receive a :class:`.Query` -object and return a new one. The :class:`.Query` object includes a -method :meth:`.with_transformation` that returns a new :class:`.Query` -transformed by the given function. +A *transformer* is an object which can receive a :class:`.Query` object and +return a new one. The :class:`.Query` object includes a method +:meth:`.with_transformation` that returns a new :class:`.Query` transformed by +the given function. We can combine this with the :class:`.Comparator` class to produce one type of recipe which can both set up the FROM clause of a query as well as assign filtering criterion. -Consider a mapped class ``Node``, which assembles using adjacency list -into a hierarchical tree pattern:: +Consider a mapped class ``Node``, which assembles using adjacency list into a +hierarchical tree pattern:: from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship @@ -654,9 +651,9 @@ into a hierarchical tree pattern:: parent_id = Column(Integer, ForeignKey('node.id')) parent = relationship("Node", remote_side=id) -Suppose we wanted to add an accessor ``grandparent``. This would -return the ``parent`` of ``Node.parent``. When we have an instance of -``Node``, this is simple:: +Suppose we wanted to add an accessor ``grandparent``. This would return the +``parent`` of ``Node.parent``. When we have an instance of ``Node``, this is +simple:: from sqlalchemy.ext.hybrid import hybrid_property @@ -667,13 +664,12 @@ return the ``parent`` of ``Node.parent``. When we have an instance of def grandparent(self): return self.parent.parent -For the expression, things are not so clear. We'd need to construct -a :class:`.Query` where we :meth:`~.Query.join` twice along -``Node.parent`` to get to the ``grandparent``. We can instead return -a transforming callable that we'll combine with the -:class:`.Comparator` class to receive any :class:`.Query` object, and -return a new one that's joined to the ``Node.parent`` attribute and -filtered based on the given criterion:: +For the expression, things are not so clear. We'd need to construct a +:class:`.Query` where we :meth:`~.Query.join` twice along ``Node.parent`` to +get to the ``grandparent``. We can instead return a transforming callable +that we'll combine with the :class:`.Comparator` class to receive any +:class:`.Query` object, and return a new one that's joined to the +``Node.parent`` attribute and filtered based on the given criterion:: from sqlalchemy.ext.hybrid import Comparator @@ -702,17 +698,15 @@ filtered based on the given criterion:: def grandparent(cls): return GrandparentTransformer(cls) -The ``GrandparentTransformer`` overrides the core -:meth:`.Operators.operate` method at the base of the -:class:`.Comparator` hierarchy to return a query-transforming -callable, which then runs the given comparison operation in a -particular context. Such as, in the example above, the ``operate`` -method is called, given the :attr:`.Operators.eq` callable as well as -the right side of the comparison ``Node(id=5)``. A function -``transform`` is then returned which will transform a :class:`.Query` -first to join to ``Node.parent``, then to compare ``parent_alias`` -using :attr:`.Operators.eq` against the left and right sides, passing -into :class:`.Query.filter`: +The ``GrandparentTransformer`` overrides the core :meth:`.Operators.operate` +method at the base of the :class:`.Comparator` hierarchy to return a query- +transforming callable, which then runs the given comparison operation in a +particular context. Such as, in the example above, the ``operate`` method is +called, given the :attr:`.Operators.eq` callable as well as the right side of +the comparison ``Node(id=5)``. A function ``transform`` is then returned which +will transform a :class:`.Query` first to join to ``Node.parent``, then to +compare ``parent_alias`` using :attr:`.Operators.eq` against the left and right +sides, passing into :class:`.Query.filter`: .. sourcecode:: pycon+sql @@ -726,12 +720,12 @@ into :class:`.Query.filter`: WHERE :param_1 = node_1.parent_id {stop} -We can modify the pattern to be more verbose but flexible by separating -the "join" step from the "filter" step. The tricky part here is ensuring -that successive instances of ``GrandparentTransformer`` use the same +We can modify the pattern to be more verbose but flexible by separating the +"join" step from the "filter" step. The tricky part here is ensuring that +successive instances of ``GrandparentTransformer`` use the same :class:`.AliasedClass` object against ``Node``. Below we use a simple -memoizing approach that associates a ``GrandparentTransformer`` -with each class:: +memoizing approach that associates a ``GrandparentTransformer`` with each +class:: class Node(Base): @@ -769,12 +763,12 @@ with each class:: WHERE :param_1 = node_1.parent_id {stop} -The "transformer" pattern is an experimental pattern that starts -to make usage of some functional programming paradigms. -While it's only recommended for advanced and/or patient developers, -there's probably a whole lot of amazing things it can be used for. +The "transformer" pattern is an experimental pattern that starts to make usage +of some functional programming paradigms. While it's only recommended for +advanced and/or patient developers, there's probably a whole lot of amazing +things it can be used for. -""" +""" # noqa from .. import util from ..orm import attributes from ..orm import interfaces diff --git a/lib/sqlalchemy/ext/mutable.py b/lib/sqlalchemy/ext/mutable.py index 2a57d563b..96372639f 100644 --- a/lib/sqlalchemy/ext/mutable.py +++ b/lib/sqlalchemy/ext/mutable.py @@ -483,7 +483,7 @@ class MutableBase(object): if not attrs or listen_keys.intersection(attrs): load(state) - def set(target, value, oldvalue, initiator): + def set_(target, value, oldvalue, initiator): """Listen for set/replace events on the target data member. @@ -523,7 +523,7 @@ class MutableBase(object): parent_cls, "refresh_flush", load_attrs, raw=True, propagate=True ) event.listen( - attribute, "set", set, raw=True, retval=True, propagate=True + attribute, "set", set_, raw=True, retval=True, propagate=True ) event.listen(parent_cls, "pickle", pickle, raw=True, propagate=True) event.listen( diff --git a/lib/sqlalchemy/ext/serializer.py b/lib/sqlalchemy/ext/serializer.py index 632311b7a..ae983946a 100644 --- a/lib/sqlalchemy/ext/serializer.py +++ b/lib/sqlalchemy/ext/serializer.py @@ -81,29 +81,29 @@ def Serializer(*args, **kw): if isinstance(obj, QueryableAttribute): cls = obj.impl.class_ key = obj.impl.key - id = "attribute:" + key + ":" + b64encode(pickle.dumps(cls)) + id_ = "attribute:" + key + ":" + b64encode(pickle.dumps(cls)) elif isinstance(obj, Mapper) and not obj.non_primary: - id = "mapper:" + b64encode(pickle.dumps(obj.class_)) + id_ = "mapper:" + b64encode(pickle.dumps(obj.class_)) elif isinstance(obj, MapperProperty) and not obj.parent.non_primary: - id = ( + id_ = ( "mapperprop:" + b64encode(pickle.dumps(obj.parent.class_)) + ":" + obj.key ) elif isinstance(obj, Table): - id = "table:" + text_type(obj.key) + id_ = "table:" + text_type(obj.key) elif isinstance(obj, Column) and isinstance(obj.table, Table): - id = ( + id_ = ( "column:" + text_type(obj.table.key) + ":" + text_type(obj.key) ) elif isinstance(obj, Session): - id = "session:" + id_ = "session:" elif isinstance(obj, Engine): - id = "engine:" + id_ = "engine:" else: return None - return id + return id_ pickler.persistent_id = persistent_id return pickler @@ -127,8 +127,8 @@ def Deserializer(file, metadata=None, scoped_session=None, engine=None): else: return None - def persistent_load(id): - m = our_ids.match(text_type(id)) + def persistent_load(id_): + m = our_ids.match(text_type(id_)) if not m: return None else: diff --git a/lib/sqlalchemy/orm/interfaces.py b/lib/sqlalchemy/orm/interfaces.py index e846e05c0..fbdd3c09a 100644 --- a/lib/sqlalchemy/orm/interfaces.py +++ b/lib/sqlalchemy/orm/interfaces.py @@ -27,6 +27,7 @@ from .base import _MappedAttribute from .base import EXT_CONTINUE from .base import EXT_STOP from .base import InspectionAttr +from .base import InspectionAttrInfo from .base import MANYTOMANY from .base import MANYTOONE from .base import NOT_EXTENSION |