diff options
author | Mike Bayer <mike_mp@zzzcomputing.com> | 2018-12-30 23:53:36 -0500 |
---|---|---|
committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2019-01-05 12:53:38 -0500 |
commit | eba16588f2e41d458eb982688140d1cb0b89b27f (patch) | |
tree | 0dc8b4c673ee0ad381b28a45cebbdbd2b3671883 | |
parent | 6673a213daa02ade815d00a19e39edc6cee1466a (diff) | |
download | sqlalchemy-eba16588f2e41d458eb982688140d1cb0b89b27f.tar.gz |
partial cherry-pick of master flake8. clean cherrypick for lib and test,
manually merged exaples.
Change-Id: I9532d3b13d13f2769e6ca48eea23dd7d4041f68f
(cherry picked from commit e3bdd80c6661c0e95fb67998c57540be667ce761)
66 files changed, 313 insertions, 233 deletions
diff --git a/examples/association/basic_association.py b/examples/association/basic_association.py index 56f676450..d2271ad43 100644 --- a/examples/association/basic_association.py +++ b/examples/association/basic_association.py @@ -24,6 +24,7 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/dogpile_caching/__init__.py b/examples/dogpile_caching/__init__.py index 0f19854e9..91105dc02 100644 --- a/examples/dogpile_caching/__init__.py +++ b/examples/dogpile_caching/__init__.py @@ -1,13 +1,8 @@ """ -Illustrates how to embed `dogpile.cache <https://dogpilecache.readthedocs.io/>`_ -functionality within -the :class:`.Query` object, allowing full cache control as well as the -ability to pull "lazy loaded" attributes from long term cache -as well. - -.. versionchanged:: 0.8 The example was modernized to use - dogpile.cache, replacing Beaker as the caching library in - use. +Illustrates how to embed +`dogpile.cache <https://dogpilecache.readthedocs.io/>`_ +functionality within the :class:`.Query` object, allowing full cache control +as well as the ability to pull "lazy loaded" attributes from long term cache. In this demo, the following techniques are illustrated: diff --git a/examples/dogpile_caching/advanced.py b/examples/dogpile_caching/advanced.py index 92733b721..d2ef82556 100644 --- a/examples/dogpile_caching/advanced.py +++ b/examples/dogpile_caching/advanced.py @@ -70,7 +70,8 @@ print(", ".join([p.name for p in load_name_range(25, 40, True)])) # illustrate the address loading from either cache/already # on the Person print( - "\n\nPeople plus addresses, two through twelve, addresses possibly from cache" + "\n\nPeople plus addresses, two through twelve, addresses " + "possibly from cache" ) for p in load_name_range(2, 12): print(p.format_full()) diff --git a/examples/dogpile_caching/caching_query.py b/examples/dogpile_caching/caching_query.py index 1b85d7487..3d528b880 100644 --- a/examples/dogpile_caching/caching_query.py +++ b/examples/dogpile_caching/caching_query.py @@ -18,6 +18,7 @@ dogpile.cache constructs. """ from dogpile.cache.api import NO_VALUE + from sqlalchemy.orm.interfaces import MapperOption from sqlalchemy.orm.query import Query @@ -187,14 +188,14 @@ class FromCache(MapperOption): """Construct a new FromCache. :param region: the cache region. Should be a - region configured in the dictionary of dogpile - regions. + region configured in the dictionary of dogpile + regions. :param cache_key: optional. A string cache key - that will serve as the key to the query. Use this - if your query has a huge amount of parameters (such - as when using in_()) which correspond more simply to - some other identifier. + that will serve as the key to the query. Use this + if your query has a huge amount of parameters (such + as when using in_()) which correspond more simply to + some other identifier. """ self.region = region @@ -215,14 +216,14 @@ class RelationshipCache(MapperOption): """Construct a new RelationshipCache. :param attribute: A Class.attribute which - indicates a particular class relationship() whose - lazy loader should be pulled from the cache. + indicates a particular class relationship() whose + lazy loader should be pulled from the cache. :param region: name of the cache region. :param cache_key: optional. A string cache key - that will serve as the key to the query, bypassing - the usual means of forming a key from the Query itself. + that will serve as the key to the query, bypassing + the usual means of forming a key from the Query itself. """ self.region = region diff --git a/examples/dogpile_caching/environment.py b/examples/dogpile_caching/environment.py index 6e34315b5..1dbaf01d0 100644 --- a/examples/dogpile_caching/environment.py +++ b/examples/dogpile_caching/environment.py @@ -7,6 +7,7 @@ import os import sys from dogpile.cache.region import make_region + from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session @@ -17,7 +18,7 @@ from . import caching_query py2k = sys.version_info < (3, 0) if py2k: - input = raw_input + input = raw_input # noqa # dogpile cache regions. A home base for cache configurations. regions = {} diff --git a/examples/dogpile_caching/fixture_data.py b/examples/dogpile_caching/fixture_data.py index 3bc6790d9..8387a2cb2 100644 --- a/examples/dogpile_caching/fixture_data.py +++ b/examples/dogpile_caching/fixture_data.py @@ -1,6 +1,6 @@ -"""Installs some sample data. Here we have a handful of postal codes for a few US/ -Canadian cities. Then, 100 Person records are installed, each with a -randomly selected postal code. +"""Installs some sample data. Here we have a handful of postal codes for +a few US/Canadian cities. Then, 100 Person records are installed, each +with a randomly selected postal code. """ import random diff --git a/examples/dogpile_caching/helloworld.py b/examples/dogpile_caching/helloworld.py index 848209486..6b03afbdb 100644 --- a/examples/dogpile_caching/helloworld.py +++ b/examples/dogpile_caching/helloworld.py @@ -6,6 +6,7 @@ from .caching_query import FromCache from .environment import Session from .model import Person + # load Person objects. cache the result in the "default" cache region print("loading people....") people = Session.query(Person).options(FromCache("default")).all() diff --git a/examples/dogpile_caching/relationship_caching.py b/examples/dogpile_caching/relationship_caching.py index 76c22f3c1..e3dece1ef 100644 --- a/examples/dogpile_caching/relationship_caching.py +++ b/examples/dogpile_caching/relationship_caching.py @@ -15,6 +15,7 @@ from .environment import Session from .model import cache_address_bits from .model import Person + for p in Session.query(Person).options( joinedload(Person.addresses), cache_address_bits ): diff --git a/examples/dynamic_dict/dynamic_dict.py b/examples/dynamic_dict/dynamic_dict.py index c35931535..63a23bffb 100644 --- a/examples/dynamic_dict/dynamic_dict.py +++ b/examples/dynamic_dict/dynamic_dict.py @@ -1,3 +1,13 @@ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import sessionmaker + + class ProxyDict(object): def __init__(self, parent, collection_name, childclass, keyname): self.parent = parent @@ -29,15 +39,6 @@ class ProxyDict(object): self.collection.append(value) -from sqlalchemy import Column -from sqlalchemy import create_engine -from sqlalchemy import ForeignKey -from sqlalchemy import Integer -from sqlalchemy import String -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import relationship -from sqlalchemy.orm import sessionmaker - engine = create_engine("sqlite://", echo=True) Base = declarative_base(engine) diff --git a/examples/elementtree/adjacency_list.py b/examples/elementtree/adjacency_list.py index ee92cdaba..a005fcca3 100644 --- a/examples/elementtree/adjacency_list.py +++ b/examples/elementtree/adjacency_list.py @@ -1,4 +1,6 @@ -"""Illustrates an explicit way to persist an XML document expressed using ElementTree. +""" +Illustrates an explicit way to persist an XML document expressed using +ElementTree. Each DOM node is stored in an individual table row, with attributes represented in a separate table. The @@ -8,13 +10,13 @@ along any path with a given structure of attributes, basically a (very narrow) subset of xpath. This example explicitly marshals/unmarshals the ElementTree document into -mapped entities which have their own tables. Compare to pickle.py which -uses pickle to accomplish the same task. Note that the usage of both -styles of persistence are identical, as is the structure of the main Document class. +mapped entities which have their own tables. Compare to pickle.py which uses +pickle to accomplish the same task. Note that the usage of both styles of +persistence are identical, as is the structure of the main Document class. """ -################################# PART I - Imports/Coniguration #################################### +# PART I - Imports/Configuration import io import os import re @@ -37,7 +39,7 @@ from sqlalchemy.orm import Session e = create_engine("sqlite://") meta = MetaData() -################################# PART II - Table Metadata ######################################### +# PART II - Table Metadata # stores a top level record of an XML document. documents = Table( @@ -77,10 +79,12 @@ attributes = Table( meta.create_all(e) -#################################### PART III - Model ############################################# +# PART III - Model # our document class. contains a string name, # and the ElementTree root element. + + class Document(object): def __init__(self, name, element): self.filename = name @@ -92,19 +96,22 @@ class Document(object): return buf.getvalue() -#################################### PART IV - Persistence Mapping ################################# +# PART IV - Persistence Mapping + +# Node class. a non-public class which will represent the DB-persisted +# Element/SubElement object. We cannot create mappers for ElementTree elements +# directly because they are at the very least not new-style classes, and also +# may be backed by native implementations. so here we construct an adapter. + -# Node class. a non-public class which will represent -# the DB-persisted Element/SubElement object. We cannot create mappers for -# ElementTree elements directly because they are at the very least not new-style -# classes, and also may be backed by native implementations. -# so here we construct an adapter. class _Node(object): pass -# Attribute class. also internal, this will represent the key/value attributes stored for -# a particular Node. +# Attribute class. also internal, this will represent the key/value attributes +# stored for a particular Node. + + class _Attribute(object): def __init__(self, name, value): self.name = name @@ -132,9 +139,12 @@ mapper( mapper(_Attribute, attributes) -# define marshalling functions that convert from _Node/_Attribute to/from ElementTree objects. -# this will set the ElementTree element as "document._element", and append the root _Node -# object to the "_root" mapped collection. +# define marshalling functions that convert from _Node/_Attribute to/from +# ElementTree objects. this will set the ElementTree element as +# "document._element", and append the root _Node object to the "_root" mapped +# collection. + + class ElementTreeMarshal(object): def __get__(self, document, owner): if document is None: @@ -182,7 +192,7 @@ class ElementTreeMarshal(object): # override Document's "element" attribute with the marshaller. Document.element = ElementTreeMarshal() -########################################### PART V - Basic Persistence Example ##################### +# PART V - Basic Persistence Example line = "\n--------------------------------------------------------" @@ -204,7 +214,7 @@ document = session.query(Document).filter_by(filename="test.xml").first() print(document) -############################################ PART VI - Searching for Paths ######################### +# PART VI - Searching for Paths # manually search for a document which contains "/somefile/header/field1:hi" d = ( @@ -220,6 +230,8 @@ d = ( print(d) # generalize the above approach into an extremely impoverished xpath function: + + def find_document(path, compareto): j = documents prev_elements = None diff --git a/examples/elementtree/optimized_al.py b/examples/elementtree/optimized_al.py index 586a0be32..e4fbb2ef8 100644 --- a/examples/elementtree/optimized_al.py +++ b/examples/elementtree/optimized_al.py @@ -7,7 +7,8 @@ """ -##################### PART I - Imports/Configuration ######################### +# PART I - Imports/Configuration + import io import os import re @@ -30,7 +31,7 @@ from sqlalchemy.orm import Session e = create_engine("sqlite://", echo=True) meta = MetaData() -####################### PART II - Table Metadata ############################# +# PART II - Table Metadata # stores a top level record of an XML document. documents = Table( @@ -70,10 +71,12 @@ attributes = Table( meta.create_all(e) -########################### PART III - Model ################################# +# PART III - Model # our document class. contains a string name, # and the ElementTree root element. + + class Document(object): def __init__(self, name, element): self.filename = name @@ -85,19 +88,22 @@ class Document(object): return buf.getvalue() -########################## PART IV - Persistence Mapping ##################### +# PART IV - Persistence Mapping + +# Node class. a non-public class which will represent the DB-persisted +# Element/SubElement object. We cannot create mappers for ElementTree elements +# directly because they are at the very least not new-style classes, and also +# may be backed by native implementations. so here we construct an adapter. + -# Node class. a non-public class which will represent -# the DB-persisted Element/SubElement object. We cannot create mappers for -# ElementTree elements directly because they are at the very least not new-style -# classes, and also may be backed by native implementations. -# so here we construct an adapter. class _Node(object): pass -# Attribute class. also internal, this will represent the key/value attributes stored for -# a particular Node. +# Attribute class. also internal, this will represent the key/value attributes +# stored for a particular Node. + + class _Attribute(object): def __init__(self, name, value): self.name = name @@ -117,10 +123,11 @@ mapper( }, ) -# the _Node objects change the way they load so that a list of _Nodes will organize -# themselves hierarchically using the ElementTreeMarshal. this depends on the ordering of -# nodes being hierarchical as well; relationship() always applies at least ROWID/primary key -# ordering to rows which will suffice. +# the _Node objects change the way they load so that a list of _Nodes will +# organize themselves hierarchically using the ElementTreeMarshal. this +# depends on the ordering of nodes being hierarchical as well; relationship() +# always applies at least ROWID/primary key ordering to rows which will +# suffice. mapper( _Node, elements, @@ -136,9 +143,12 @@ mapper( mapper(_Attribute, attributes) -# define marshalling functions that convert from _Node/_Attribute to/from ElementTree objects. -# this will set the ElementTree element as "document._element", and append the root _Node -# object to the "_nodes" mapped collection. +# define marshalling functions that convert from _Node/_Attribute to/from +# ElementTree objects. this will set the ElementTree element as +# "document._element", and append the root _Node object to the "_nodes" mapped +# collection. + + class ElementTreeMarshal(object): def __get__(self, document, owner): if document is None: @@ -190,7 +200,7 @@ class ElementTreeMarshal(object): # override Document's "element" attribute with the marshaller. Document.element = ElementTreeMarshal() -###################### PART V - Basic Persistence Example #################### +# PART V - Basic Persistence Example line = "\n--------------------------------------------------------" @@ -212,7 +222,7 @@ document = session.query(Document).filter_by(filename="test.xml").first() print(document) -######################## PART VI - Searching for Paths ####################### +# PART VI - Searching for Paths # manually search for a document which contains "/somefile/header/field1:hi" print("\nManual search for /somefile/header/field1=='hi':", line) @@ -229,6 +239,8 @@ d = ( print(d) # generalize the above approach into an extremely impoverished xpath function: + + def find_document(path, compareto): j = documents prev_elements = None diff --git a/examples/elementtree/pickle.py b/examples/elementtree/pickle.py index cf3ea3c88..ca2c65504 100644 --- a/examples/elementtree/pickle.py +++ b/examples/elementtree/pickle.py @@ -1,9 +1,13 @@ -"""illustrates a quick and dirty way to persist an XML document expressed using ElementTree and pickle. +""" +illustrates a quick and dirty way to persist an XML document expressed using +ElementTree and pickle. This is a trivial example using PickleType to marshal/unmarshal the ElementTree -document into a binary column. Compare to explicit.py which stores the individual components of the ElementTree -structure in distinct rows using two additional mapped entities. Note that the usage of both -styles of persistence are identical, as is the structure of the main Document class. +document into a binary column. Compare to explicit.py which stores the +individual components of the ElementTree structure in distinct rows using two +additional mapped entities. Note that the usage of both styles of persistence +are identical, as is the structure of the main Document class. + """ import os @@ -20,11 +24,14 @@ from sqlalchemy import Table from sqlalchemy.orm import mapper from sqlalchemy.orm import Session + e = create_engine("sqlite://") meta = MetaData() # setup a comparator for the PickleType since it's a mutable # element. + + def are_elements_equal(x, y): return x == y @@ -43,6 +50,8 @@ meta.create_all(e) # our document class. contains a string name, # and the ElementTree root element. + + class Document(object): def __init__(self, name, element): self.filename = name @@ -52,7 +61,7 @@ class Document(object): # setup mapper. mapper(Document, documents) -###### time to test ! ######### +# time to test ! # get ElementTree document filename = os.path.join(os.path.dirname(__file__), "test.xml") diff --git a/examples/generic_associations/__init__.py b/examples/generic_associations/__init__.py index 9d103b73e..dd6f5321b 100644 --- a/examples/generic_associations/__init__.py +++ b/examples/generic_associations/__init__.py @@ -15,4 +15,4 @@ are modernized versions of recipes presented in the 2007 blog post .. autosource:: -""" +""" # noqa diff --git a/examples/graphs/directed_graph.py b/examples/graphs/directed_graph.py index b40dbe39d..d6611eaa7 100644 --- a/examples/graphs/directed_graph.py +++ b/examples/graphs/directed_graph.py @@ -8,6 +8,7 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker + Base = declarative_base() diff --git a/examples/inheritance/joined.py b/examples/inheritance/joined.py index 09fc1a0cf..74a6e3649 100644 --- a/examples/inheritance/joined.py +++ b/examples/inheritance/joined.py @@ -12,6 +12,7 @@ from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm import with_polymorphic + Base = declarative_base() diff --git a/examples/inheritance/single.py b/examples/inheritance/single.py index 3466611eb..0d5871cb1 100644 --- a/examples/inheritance/single.py +++ b/examples/inheritance/single.py @@ -13,6 +13,7 @@ from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm import with_polymorphic + Base = declarative_base() diff --git a/examples/join_conditions/cast.py b/examples/join_conditions/cast.py index d4801fab2..e175bc227 100644 --- a/examples/join_conditions/cast.py +++ b/examples/join_conditions/cast.py @@ -29,9 +29,16 @@ in order to note to the ORM that ``B.a_id`` should be treated like the "foreign key" column. """ -from sqlalchemy import * + +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy import TypeDecorator from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import * +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/join_conditions/threeway.py b/examples/join_conditions/threeway.py index 342a6cf89..aca3b0c2f 100644 --- a/examples/join_conditions/threeway.py +++ b/examples/join_conditions/threeway.py @@ -33,9 +33,18 @@ a Query (or a :func:`.relationship`). """ -from sqlalchemy import * +from sqlalchemy import and_ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import join +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import * +from sqlalchemy.orm import foreign +from sqlalchemy.orm import mapper +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/large_collection/large_collection.py b/examples/large_collection/large_collection.py index 2cdb63bbb..9e4c47e0c 100644 --- a/examples/large_collection/large_collection.py +++ b/examples/large_collection/large_collection.py @@ -56,8 +56,8 @@ mapper( # Member objects "belong" to their parent, are deleted when # removed from the collection cascade="all, delete-orphan", - # "delete, delete-orphan" cascade does not load in objects on delete, - # allows ON DELETE CASCADE to handle it. + # "delete, delete-orphan" cascade does not load in objects on + # delete, allows ON DELETE CASCADE to handle it. # this only works with a database that supports ON DELETE CASCADE - # *not* sqlite or MySQL with MyISAM passive_deletes=True, @@ -108,7 +108,8 @@ if __name__ == "__main__": # disappear automatically without the need for additional SQL. sess.delete(org) print( - "-------------------------\nflush three - delete org, delete members in one statement\n" + "-------------------------\nflush three - delete org, " + "delete members in one statement\n" ) sess.commit() diff --git a/examples/materialized_paths/materialized_paths.py b/examples/materialized_paths/materialized_paths.py index 0bea6ccdf..f777f131b 100644 --- a/examples/materialized_paths/materialized_paths.py +++ b/examples/materialized_paths/materialized_paths.py @@ -40,6 +40,7 @@ from sqlalchemy.orm import remote from sqlalchemy.orm import Session from sqlalchemy.sql.expression import cast + Base = declarative_base() diff --git a/examples/performance/__init__.py b/examples/performance/__init__.py index b817c313a..f1f59026c 100644 --- a/examples/performance/__init__.py +++ b/examples/performance/__init__.py @@ -31,8 +31,8 @@ individual suites to be run:: -h, --help show this help message and exit --test TEST run specific test name --dburl DBURL database URL, default sqlite:///profile.db - --num NUM Number of iterations/items/etc for tests; default is 0 - module-specific + --num NUM Number of iterations/items/etc for tests; + default is module-specific --profile run profiling and dump call counts --dump dump full call profile (implies --profile) --runsnake invoke runsnakerun (implies --profile) @@ -217,7 +217,7 @@ As well as see RunSnake output for an individual test:: $ python test_loads.py --num 100 --runsnake --test test_joinedload -""" +""" # noqa import argparse import cProfile import os diff --git a/examples/performance/__main__.py b/examples/performance/__main__.py index 945458651..aeb124e1d 100644 --- a/examples/performance/__main__.py +++ b/examples/performance/__main__.py @@ -2,5 +2,6 @@ from . import Profiler + if __name__ == "__main__": Profiler.main() diff --git a/examples/performance/bulk_inserts.py b/examples/performance/bulk_inserts.py index 872381376..7908418b1 100644 --- a/examples/performance/bulk_inserts.py +++ b/examples/performance/bulk_inserts.py @@ -10,6 +10,8 @@ from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session +from . import Profiler + from . import Profiler diff --git a/examples/performance/bulk_updates.py b/examples/performance/bulk_updates.py index 5f5b0ec14..aa3c6be83 100644 --- a/examples/performance/bulk_updates.py +++ b/examples/performance/bulk_updates.py @@ -9,6 +9,8 @@ from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session +from . import Profiler + from . import Profiler diff --git a/examples/performance/large_resultsets.py b/examples/performance/large_resultsets.py index 835b063c1..993b79453 100644 --- a/examples/performance/large_resultsets.py +++ b/examples/performance/large_resultsets.py @@ -23,6 +23,7 @@ from sqlalchemy.orm import Session from . import Profiler + Base = declarative_base() engine = None @@ -169,8 +170,8 @@ def _test_dbapi_raw(n, make_objects): # going to do this, so see how this pushes you right back into # ORM land anyway :) class SimpleCustomer(object): - def __init__(self, id, name, description): - self.id = id + def __init__(self, id_, name, description): + self.id = id_ self.name = name self.description = description diff --git a/examples/performance/short_selects.py b/examples/performance/short_selects.py index 3ea11f0d1..afa3212b2 100644 --- a/examples/performance/short_selects.py +++ b/examples/performance/short_selects.py @@ -18,6 +18,7 @@ from sqlalchemy.orm import Session from . import Profiler + Base = declarative_base() engine = None diff --git a/examples/performance/single_inserts.py b/examples/performance/single_inserts.py index eb035de5b..514494576 100644 --- a/examples/performance/single_inserts.py +++ b/examples/performance/single_inserts.py @@ -12,6 +12,8 @@ from sqlalchemy import pool from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session +from . import Profiler + from . import Profiler diff --git a/examples/postgis/__init__.py b/examples/postgis/__init__.py index 66ae65d3c..963a561f3 100644 --- a/examples/postgis/__init__.py +++ b/examples/postgis/__init__.py @@ -31,7 +31,8 @@ and simple to use extension points. E.g.:: - print session.query(Road).filter(Road.road_geom.intersects(r1.road_geom)).all() + print session.query(Road).filter( + Road.road_geom.intersects(r1.road_geom)).all() .. autosource:: diff --git a/examples/postgis/postgis.py b/examples/postgis/postgis.py index bcea822b3..8f5acc7a2 100644 --- a/examples/postgis/postgis.py +++ b/examples/postgis/postgis.py @@ -281,7 +281,8 @@ if __name__ == "__main__": ] ) - # or use an explicit TextualGisElement (similar to saying func.GeomFromText()) + # or use an explicit TextualGisElement + # (similar to saying func.GeomFromText()) r = Road( road_name="Dave Cres", road_geom=TextualGisElement( @@ -295,7 +296,8 @@ if __name__ == "__main__": session.commit() - # after flush and/or commit, all the TextualGisElements become PersistentGisElements. + # after flush and/or commit, all the TextualGisElements + # become PersistentGisElements. assert str(r.road_geom) == "LINESTRING(198231 263418,198213 268322)" r1 = session.query(Road).filter(Road.road_name == "Graeme Ave").one() @@ -321,16 +323,16 @@ if __name__ == "__main__": ) print(session.execute(stmt).fetchall()) - # TODO: for some reason the auto-generated labels have the internal replacement - # strings exposed, even though PG doesn't complain + # TODO: for some reason the auto-generated labels have the internal + # replacement strings exposed, even though PG doesn't complain # look up the hex binary version, using SQLAlchemy casts as_binary = session.scalar( select([type_coerce(r.road_geom, Geometry(coerce_="binary"))]) ) - assert ( - as_binary.as_hex - == "01020000000200000000000000b832084100000000e813104100000000283208410000000088601041" + assert as_binary.as_hex == ( + "01020000000200000000000000b832084100000000" + "e813104100000000283208410000000088601041" ) # back again, same method ! diff --git a/examples/sharding/__init__.py b/examples/sharding/__init__.py index 59d26a217..eb8e10686 100644 --- a/examples/sharding/__init__.py +++ b/examples/sharding/__init__.py @@ -8,7 +8,7 @@ The basic components of a "sharded" mapping are: * a function which can return a single shard id, given an instance to be saved; this is called "shard_chooser" * a function which can return a list of shard ids which apply to a particular - instance identifier; this is called "id_chooser". If it returns all shard ids, + instance identifier; this is called "id_chooser".If it returns all shard ids, all shards will be searched. * a function which can return a list of shard ids to try, given a particular Query ("query_chooser"). If it returns all shard ids, all shards will be diff --git a/examples/versioned_history/__init__.py b/examples/versioned_history/__init__.py index 7670cd613..e6db1fc2c 100644 --- a/examples/versioned_history/__init__.py +++ b/examples/versioned_history/__init__.py @@ -1,7 +1,7 @@ """ Illustrates an extension which creates version tables for entities and stores -records for each change. The given extensions generate an anonymous "history" class which -represents historical versions of the target object. +records for each change. The given extensions generate an anonymous "history" +class which represents historical versions of the target object. Compare to the :ref:`examples_versioned_rows` examples which write updates as new rows in the same table, without using a separate history table. diff --git a/examples/versioned_history/history_meta.py b/examples/versioned_history/history_meta.py index e2bcdc90d..61853cbf9 100644 --- a/examples/versioned_history/history_meta.py +++ b/examples/versioned_history/history_meta.py @@ -173,20 +173,19 @@ def _history_mapper(local_mapper): class Versioned(object): @declared_attr def __mapper_cls__(cls): - def map(cls, *arg, **kw): + def map_(cls, *arg, **kw): mp = mapper(cls, *arg, **kw) _history_mapper(mp) return mp - - return map + return map_ __table_args__ = {"sqlite_autoincrement": True} """Use sqlite_autoincrement, to ensure unique integer values are used for new rows even for rows taht have been deleted.""" -def versioned_objects(iter): - for obj in iter: +def versioned_objects(iter_): + for obj in iter_: if hasattr(obj, "__history_mapper__"): yield obj diff --git a/lib/sqlalchemy/databases/__init__.py b/lib/sqlalchemy/databases/__init__.py index dbdd1e0d1..ca31bdd06 100644 --- a/lib/sqlalchemy/databases/__init__.py +++ b/lib/sqlalchemy/databases/__init__.py @@ -20,6 +20,9 @@ from ..dialects.sybase import base as sybase postgres = postgresql +postgres = postgresql + + __all__ = ( "firebird", "mssql", diff --git a/lib/sqlalchemy/dialects/firebird/fdb.py b/lib/sqlalchemy/dialects/firebird/fdb.py index 5bf3d2c49..83ca5221b 100644 --- a/lib/sqlalchemy/dialects/firebird/fdb.py +++ b/lib/sqlalchemy/dialects/firebird/fdb.py @@ -9,8 +9,7 @@ .. dialect:: firebird+fdb :name: fdb :dbapi: pyodbc - :connectstring: firebird+fdb://user:password@host:port/path/to/db\ -[?key=value&key=value...] + :connectstring: firebird+fdb://user:password@host:port/path/to/db[?key=value&key=value...] :url: http://pypi.python.org/pypi/fdb/ fdb is a kinterbasdb compatible DBAPI for Firebird. @@ -66,7 +65,7 @@ accept every argument that Kinterbasdb does. http://pythonhosted.org/fdb/usage-guide.html#retaining-transactions - information on the "retaining" flag. -""" +""" # noqa from .kinterbasdb import FBDialect_kinterbasdb from ... import util diff --git a/lib/sqlalchemy/dialects/firebird/kinterbasdb.py b/lib/sqlalchemy/dialects/firebird/kinterbasdb.py index 4dde6788d..8adce847e 100644 --- a/lib/sqlalchemy/dialects/firebird/kinterbasdb.py +++ b/lib/sqlalchemy/dialects/firebird/kinterbasdb.py @@ -9,8 +9,7 @@ .. dialect:: firebird+kinterbasdb :name: kinterbasdb :dbapi: kinterbasdb - :connectstring: firebird+kinterbasdb://user:password@host:port/path/to/db\ -[?key=value&key=value...] + :connectstring: firebird+kinterbasdb://user:password@host:port/path/to/db[?key=value&key=value...] :url: http://firebirdsql.org/index.php?op=devel&sub=python Arguments @@ -36,7 +35,7 @@ In addition, it also accepts the following: http://kinterbasdb.sourceforge.net/dist_docs/usage.html#special_issue_concurrency -""" +""" # noqa import decimal from re import match diff --git a/lib/sqlalchemy/dialects/mysql/gaerdbms.py b/lib/sqlalchemy/dialects/mysql/gaerdbms.py index 507926a2b..23c84ec15 100644 --- a/lib/sqlalchemy/dialects/mysql/gaerdbms.py +++ b/lib/sqlalchemy/dialects/mysql/gaerdbms.py @@ -4,13 +4,12 @@ # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -""" +r""" .. dialect:: mysql+gaerdbms :name: Google Cloud SQL :dbapi: rdbms :connectstring: mysql+gaerdbms:///<dbname>?instance=<instancename> - :url: https://developers.google.com/appengine/docs/python/cloud-sql/\ -developers-guide + :url: https://developers.google.com/appengine/docs/python/cloud-sql/developers-guide This dialect is based primarily on the :mod:`.mysql.mysqldb` dialect with minimal changes. @@ -33,7 +32,7 @@ so the dialect does not pool connections. The :class:`.NullPool` implementation is installed within the :class:`.Engine` by default. -""" +""" # noqa import os import re diff --git a/lib/sqlalchemy/dialects/mysql/zxjdbc.py b/lib/sqlalchemy/dialects/mysql/zxjdbc.py index 044d34fec..3a4cee726 100644 --- a/lib/sqlalchemy/dialects/mysql/zxjdbc.py +++ b/lib/sqlalchemy/dialects/mysql/zxjdbc.py @@ -5,13 +5,12 @@ # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -""" +r""" .. dialect:: mysql+zxjdbc :name: zxjdbc for Jython :dbapi: zxjdbc - :connectstring: mysql+zxjdbc://<user>:<password>@<hostname>[:<port>]/\ -<database> + :connectstring: mysql+zxjdbc://<user>:<password>@<hostname>[:<port>]/<database> :driverurl: http://dev.mysql.com/downloads/connector/j/ .. note:: Jython is not supported by current versions of SQLAlchemy. The @@ -26,7 +25,7 @@ MySQL Connector/J JDBC driver, by default SQLAlchemy sets its ``characterEncoding`` connection property to ``UTF-8``. It may be overridden via a ``create_engine`` URL parameter. -""" +""" # noqa import re from .base import BIT diff --git a/lib/sqlalchemy/dialects/postgresql/ext.py b/lib/sqlalchemy/dialects/postgresql/ext.py index 94286fd6c..7f97d6e32 100644 --- a/lib/sqlalchemy/dialects/postgresql/ext.py +++ b/lib/sqlalchemy/dialects/postgresql/ext.py @@ -83,9 +83,9 @@ class ExcludeConstraint(ColumnCollectionConstraint): Defines an EXCLUDE constraint as described in the `postgres documentation`__. - __ http://www.postgresql.org/docs/9.0/\ -static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE - """ + __ http://www.postgresql.org/docs/9.0/static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE + + """ # noqa __visit_name__ = "exclude_constraint" diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py b/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py index 7343bc973..c31527a44 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py @@ -4,13 +4,11 @@ # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -""" +r""" .. dialect:: postgresql+psycopg2cffi :name: psycopg2cffi :dbapi: psycopg2cffi - :connectstring: \ -postgresql+psycopg2cffi://user:password@host:port/dbname\ -[?key=value&key=value...] + :connectstring: postgresql+psycopg2cffi://user:password@host:port/dbname[?key=value&key=value...] :url: http://pypi.python.org/pypi/psycopg2cffi/ ``psycopg2cffi`` is an adaptation of ``psycopg2``, using CFFI for the C @@ -23,7 +21,7 @@ is as per ``psycopg2``. :mod:`sqlalchemy.dialects.postgresql.psycopg2` -""" +""" # noqa from .psycopg2 import PGDialect_psycopg2 diff --git a/lib/sqlalchemy/dialects/postgresql/pygresql.py b/lib/sqlalchemy/dialects/postgresql/pygresql.py index 27d2a715b..13a3118b5 100644 --- a/lib/sqlalchemy/dialects/postgresql/pygresql.py +++ b/lib/sqlalchemy/dialects/postgresql/pygresql.py @@ -4,15 +4,13 @@ # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php - """ .. dialect:: postgresql+pygresql :name: pygresql :dbapi: pgdb - :connectstring: postgresql+pygresql://user:password@host:port/dbname\ -[?key=value&key=value...] + :connectstring: postgresql+pygresql://user:password@host:port/dbname[?key=value&key=value...] :url: http://www.pygresql.org/ -""" +""" # noqa import decimal import re diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlcipher.py b/lib/sqlalchemy/dialects/sqlite/pysqlcipher.py index 661587db8..66abef38f 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlcipher.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlcipher.py @@ -25,7 +25,8 @@ Driver ------ -The driver here is the `pysqlcipher <https://pypi.python.org/pypi/pysqlcipher>`_ +The driver here is the +`pysqlcipher <https://pypi.python.org/pypi/pysqlcipher>`_ driver, which makes use of the SQLCipher engine. This system essentially introduces new PRAGMA commands to SQLite which allows the setting of a passphrase and other encryption parameters, allowing the database @@ -74,7 +75,8 @@ to prevent unencrypted connections from being held open for long periods of time, at the expense of slower startup time for new connections. -""" +""" # noqa + from __future__ import absolute_import from .pysqlite import SQLiteDialect_pysqlite diff --git a/lib/sqlalchemy/dialects/sybase/pyodbc.py b/lib/sqlalchemy/dialects/sybase/pyodbc.py index 7f9d406b2..ba299befd 100644 --- a/lib/sqlalchemy/dialects/sybase/pyodbc.py +++ b/lib/sqlalchemy/dialects/sybase/pyodbc.py @@ -9,8 +9,7 @@ .. dialect:: sybase+pyodbc :name: PyODBC :dbapi: pyodbc - :connectstring: sybase+pyodbc://<username>:<password>@<dsnname>\ -[/<database>] + :connectstring: sybase+pyodbc://<username>:<password>@<dsnname>[/<database>] :url: http://pypi.python.org/pypi/pyodbc/ @@ -32,7 +31,7 @@ Currently *not* supported are:: UNITEXT UNIVARCHAR -""" +""" # noqa import decimal diff --git a/lib/sqlalchemy/dialects/sybase/pysybase.py b/lib/sqlalchemy/dialects/sybase/pysybase.py index fb7cb8365..9fedc9f26 100644 --- a/lib/sqlalchemy/dialects/sybase/pysybase.py +++ b/lib/sqlalchemy/dialects/sybase/pysybase.py @@ -9,8 +9,7 @@ .. dialect:: sybase+pysybase :name: Python-Sybase :dbapi: Sybase - :connectstring: sybase+pysybase://<username>:<password>@<dsn>/\ -[database name] + :connectstring: sybase+pysybase://<username>:<password>@<dsn>/[database name] :url: http://python-sybase.sourceforge.net/ Unicode Support @@ -19,7 +18,7 @@ Unicode Support The python-sybase driver does not appear to support non-ASCII strings of any kind at this time. -""" +""" # noqa from sqlalchemy import processors from sqlalchemy import types as sqltypes diff --git a/lib/sqlalchemy/engine/threadlocal.py b/lib/sqlalchemy/engine/threadlocal.py index e4c392c93..b34d510f7 100644 --- a/lib/sqlalchemy/engine/threadlocal.py +++ b/lib/sqlalchemy/engine/threadlocal.py @@ -93,8 +93,8 @@ class TLEngine(base.Engine): def __enter__(self): return self - def __exit__(self, type, value, traceback): - if type is None: + def __exit__(self, type_, value, traceback): + if type_ is None: self.commit() else: self.rollback() diff --git a/lib/sqlalchemy/engine/util.py b/lib/sqlalchemy/engine/util.py index 76bb8f4b5..bf8ec13b9 100644 --- a/lib/sqlalchemy/engine/util.py +++ b/lib/sqlalchemy/engine/util.py @@ -28,8 +28,8 @@ def connection_memoize(key): def py_fallback(): - def _distill_params(multiparams, params): - """Given arguments from the calling form *multiparams, **params, + def _distill_params(multiparams, params): # noqa + r"""Given arguments from the calling form \*multiparams, \**params, return a list of bind parameter structures, usually a list of dictionaries. @@ -75,6 +75,6 @@ def py_fallback(): try: - from sqlalchemy.cutils import _distill_params + from sqlalchemy.cutils import _distill_params # noqa except ImportError: globals().update(py_fallback()) diff --git a/lib/sqlalchemy/exc.py b/lib/sqlalchemy/exc.py index 832c5ee52..e47df85af 100644 --- a/lib/sqlalchemy/exc.py +++ b/lib/sqlalchemy/exc.py @@ -179,7 +179,7 @@ class InvalidatePoolError(DisconnectionError): invalidate_pool = True -class TimeoutError(SQLAlchemyError): +class TimeoutError(SQLAlchemyError): # noqa """Raised when a connection pool times out on getting a connection.""" diff --git a/lib/sqlalchemy/ext/automap.py b/lib/sqlalchemy/ext/automap.py index 545f9dfea..60cc4dfe0 100644 --- a/lib/sqlalchemy/ext/automap.py +++ b/lib/sqlalchemy/ext/automap.py @@ -512,7 +512,7 @@ the :meth:`.AutomapBase.prepare` method is required; if not called, the classes we've declared are in an un-mapped state. -""" +""" # noqa from .declarative import declarative_base as _declarative_base from .declarative.base import _DeferredMapperConfig from .. import util diff --git a/lib/sqlalchemy/ext/indexable.py b/lib/sqlalchemy/ext/indexable.py index 5d3332abc..a9100728e 100644 --- a/lib/sqlalchemy/ext/indexable.py +++ b/lib/sqlalchemy/ext/indexable.py @@ -174,10 +174,6 @@ data structure does not exist, and a set operation is called: rules. - - - - Subclassing =========== @@ -224,7 +220,7 @@ The above query will render:: FROM person WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s -""" +""" # noqa from __future__ import absolute_import from sqlalchemy import inspect diff --git a/lib/sqlalchemy/log.py b/lib/sqlalchemy/log.py index 6b0b2e90e..45073ad92 100644 --- a/lib/sqlalchemy/log.py +++ b/lib/sqlalchemy/log.py @@ -21,6 +21,7 @@ instance only. import logging import sys + # set initial level to WARN. This so that # log statements don't occur in the absence of explicit # logging being enabled for 'sqlalchemy'. @@ -73,8 +74,8 @@ class InstanceLogger(object): 'debug' -> logging.DEBUG True -> logging.INFO - False -> Effective level of underlying logger - (logging.WARNING by default) + False -> Effective level of underlying logger ( + logging.WARNING by default) None -> same as False """ diff --git a/lib/sqlalchemy/orm/identity.py b/lib/sqlalchemy/orm/identity.py index e48d540ba..8152c9884 100644 --- a/lib/sqlalchemy/orm/identity.py +++ b/lib/sqlalchemy/orm/identity.py @@ -33,7 +33,7 @@ class IdentityMap(object): in the map""" self.add(state) - def update(self, dict): + def update(self, dict_): raise NotImplementedError("IdentityMap uses add() to insert data") def clear(self): diff --git a/lib/sqlalchemy/orm/instrumentation.py b/lib/sqlalchemy/orm/instrumentation.py index 2affb237a..9dcd035ca 100644 --- a/lib/sqlalchemy/orm/instrumentation.py +++ b/lib/sqlalchemy/orm/instrumentation.py @@ -72,8 +72,8 @@ class ClassManager(dict): if mgr is not None ] - for base in self._bases: - self.update(base) + for base_ in self._bases: + self.update(base_) self.dispatch._events._new_classmanager_instance(class_, self) # events._InstanceEventsHold.populate(class_, self) diff --git a/lib/sqlalchemy/testing/config.py b/lib/sqlalchemy/testing/config.py index 5732fd0e2..5f4463765 100644 --- a/lib/sqlalchemy/testing/config.py +++ b/lib/sqlalchemy/testing/config.py @@ -6,6 +6,8 @@ # the MIT License: http://www.opensource.org/licenses/mit-license.php import collections +from unittest import SkipTest as _skip_test_exception + requirements = None db = None @@ -16,11 +18,6 @@ test_schema = None test_schema_2 = None _current = None -try: - from unittest import SkipTest as _skip_test_exception -except ImportError: - _skip_test_exception = None - class Config(object): def __init__(self, db, db_opts, options, file_config): diff --git a/lib/sqlalchemy/testing/entities.py b/lib/sqlalchemy/testing/entities.py index 42c42149c..a14304b97 100644 --- a/lib/sqlalchemy/testing/entities.py +++ b/lib/sqlalchemy/testing/entities.py @@ -6,7 +6,8 @@ # the MIT License: http://www.opensource.org/licenses/mit-license.php import sqlalchemy as sa -from sqlalchemy import exc as sa_exc +from .. import exc as sa_exc + _repr_stack = set() diff --git a/lib/sqlalchemy/testing/mock.py b/lib/sqlalchemy/testing/mock.py index 7bc4c620d..0b84d7db8 100644 --- a/lib/sqlalchemy/testing/mock.py +++ b/lib/sqlalchemy/testing/mock.py @@ -11,11 +11,20 @@ from __future__ import absolute_import from ..util import py33 + if py33: - from unittest.mock import MagicMock, Mock, call, patch, ANY + from unittest.mock import MagicMock + from unittest.mock import Mock + from unittest.mock import call + from unittest.mock import patch + from unittest.mock import ANY else: try: - from mock import MagicMock, Mock, call, patch, ANY + from mock import MagicMock # noqa + from mock import Mock # noqa + from mock import call # noqa + from mock import patch # noqa + from mock import ANY # noqa except ImportError: raise ImportError( "SQLAlchemy's test suite requires the " diff --git a/reap_dbs.py b/reap_dbs.py index 10accde90..1e4033be4 100644 --- a/reap_dbs.py +++ b/reap_dbs.py @@ -10,10 +10,12 @@ running a kill of all detected sessions does not seem to release the database in process. """ -from sqlalchemy.testing import provision import logging import sys +from sqlalchemy.testing import provision + + logging.basicConfig() logging.getLogger(provision.__name__).setLevel(logging.INFO) @@ -1,16 +1,19 @@ -import os -import platform -import re -import sys from distutils.command.build_ext import build_ext from distutils.errors import CCompilerError from distutils.errors import DistutilsExecError from distutils.errors import DistutilsPlatformError -from setuptools import Distribution as _Distribution, Extension -from setuptools import setup +import os +import platform +import re +import sys + +from setuptools import Distribution as _Distribution +from setuptools import Extension from setuptools import find_packages +from setuptools import setup from setuptools.command.test import test as TestCommand + cmdclass = {} if sys.version_info < (2, 7): raise Exception("SQLAlchemy requires Python 2.7 or higher.") diff --git a/sqla_nose.py b/sqla_nose.py index fe5c4d00b..f5d548ad2 100755 --- a/sqla_nose.py +++ b/sqla_nose.py @@ -6,9 +6,11 @@ This script is a front-end to "nosetests" which installs SQLAlchemy's testing plugin into the local environment. """ +import os import sys + import nose -import os + if not sys.flags.no_user_site: sys.path.insert( @@ -16,6 +18,7 @@ if not sys.flags.no_user_site: os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib') ) + # use bootstrapping so that test plugins are loaded # without touching the main library before coverage starts bootstrap_file = os.path.join( @@ -29,5 +32,5 @@ with open(bootstrap_file) as f: exec(code, globals(), locals()) -from noseplugin import NoseSQLAlchemy +from noseplugin import NoseSQLAlchemy # noqa nose.main(addplugins=[NoseSQLAlchemy()]) diff --git a/test/dialect/test_suite.py b/test/dialect/test_suite.py index d4e753656..bf58c6fcc 100644 --- a/test/dialect/test_suite.py +++ b/test/dialect/test_suite.py @@ -1 +1 @@ -from sqlalchemy.testing.suite import * +from sqlalchemy.testing.suite import * # noqa diff --git a/test/orm/test_composites.py b/test/orm/test_composites.py index 40254dbca..3fef87a0e 100644 --- a/test/orm/test_composites.py +++ b/test/orm/test_composites.py @@ -496,8 +496,8 @@ class PrimaryKeyTest(fixtures.MappedTest): graphs = cls.tables.graphs class Version(cls.Comparable): - def __init__(self, id, version): - self.id = id + def __init__(self, id_, version): + self.id = id_ self.version = version def __composite_values__(self): diff --git a/test/orm/test_deprecations.py b/test/orm/test_deprecations.py index 120e59c1e..195012b99 100644 --- a/test/orm/test_deprecations.py +++ b/test/orm/test_deprecations.py @@ -4,6 +4,12 @@ Collects specimens of old ORM code and explicitly covers the recommended modern (i.e. not deprecated) alternative to them. The tests snippets here can be migrated directly to the wiki, docs, etc. +.. deprecated:: + + This test suite is interested in extremely old (pre 0.5) patterns + and in modern use illustrates trivial use cases that don't need + an additional test suite. + """ from sqlalchemy import ForeignKey from sqlalchemy import func @@ -20,7 +26,7 @@ from sqlalchemy.testing.schema import Table class QueryAlternativesTest(fixtures.MappedTest): - '''Collects modern idioms for Queries + r'''Collects modern idioms for Queries The docstring for each test case serves as miniature documentation about the deprecated use case, and the test body illustrates (and covers) the @@ -30,22 +36,22 @@ class QueryAlternativesTest(fixtures.MappedTest): cases remain useful to readers even after the deprecated method has been removed from the modern codebase. - Format: + Format:: - def test_deprecated_thing(self): - """Query.methodname(old, arg, **signature) + def test_deprecated_thing(self): + """Query.methodname(old, arg, **signature) - output = session.query(User).deprecatedmethod(inputs) + output = session.query(User).deprecatedmethod(inputs) - """ + """ - # 0.4+ - output = session.query(User).newway(inputs) - assert output is correct + # 0.4+ + output = session.query(User).newway(inputs) + assert output is correct - # 0.5+ - output = session.query(User).evennewerway(inputs) - assert output is correct + # 0.5+ + output = session.query(User).evennewerway(inputs) + assert output is correct ''' @@ -169,11 +175,11 @@ class QueryAlternativesTest(fixtures.MappedTest): # 0.5.0 maxes = list(session.query(Address).values(func.max(Address.bounces))) - max = maxes[0][0] - assert max == 10 + max_ = maxes[0][0] + assert max_ == 10 - max = session.query(func.max(Address.bounces)).one()[0] - assert max == 10 + max_ = session.query(func.max(Address.bounces)).one()[0] + assert max_ == 10 def test_apply_min(self): """Query.apply_min(col) @@ -188,11 +194,11 @@ class QueryAlternativesTest(fixtures.MappedTest): # 0.5.0 mins = list(session.query(Address).values(func.min(Address.bounces))) - min = mins[0][0] - assert min == 0 + min_ = mins[0][0] + assert min_ == 0 - min = session.query(func.min(Address.bounces)).one()[0] - assert min == 0 + min_ = session.query(func.min(Address.bounces)).one()[0] + assert min_ == 0 def test_apply_avg(self): """Query.apply_avg(col) @@ -231,7 +237,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert avg == 11 def test_count_by(self): - """Query.count_by(*args, **params) + r"""Query.count_by(\*args, \**params) num = session.query(Address).count_by(purpose='Personal') @@ -255,7 +261,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert num == 3, num def test_count_whereclause(self): - """Query.count(whereclause=None, params=None, **kwargs) + r"""Query.count(whereclause=None, params=None, \**kwargs) num = session.query(Address).count(address_table.c.bounces > 1) @@ -269,7 +275,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert num == 1, num def test_execute(self): - """Query.execute(clauseelement, params=None, *args, **kwargs) + r"""Query.execute(clauseelement, params=None, \*args, \**kwargs) users = session.query(User).execute(users_table.select()) @@ -283,7 +289,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert len(users) == 4 def test_get_by(self): - """Query.get_by(*args, **params) + r"""Query.get_by(\*args, \**params) user = session.query(User).get_by(name='ed') @@ -316,7 +322,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert user.name == "fred" def test_instances_entities(self): - """Query.instances(cursor, *mappers_or_columns, **kwargs) + r"""Query.instances(cursor, \*mappers_or_columns, \**kwargs) sel = users_table.join(addresses_table).select(use_labels=True) res = session.query(User).instances(sel.execute(), Address) @@ -340,7 +346,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert isinstance(cola, User) and isinstance(colb, Address) def test_join_by(self): - """Query.join_by(*args, **params) + r"""Query.join_by(\*args, \**params) TODO """ @@ -392,7 +398,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert user.id == 1 def test_select(self): - """Query.select(arg=None, **kwargs) + r"""Query.select(arg=None, \**kwargs) users = session.query(User).select(users_table.c.name != None) @@ -406,11 +412,11 @@ class QueryAlternativesTest(fixtures.MappedTest): assert len(users) == 4 def test_select_by(self): - """Query.select_by(*args, **params) + r"""Query.select_by(\*args, \**params) users = session.query(User).select_by(name='fred') - # 0.3 magic join on *_by methods + # 0.3 magic join on \*_by methods users = session.query(User).select_by(email_address='fred@the.fred') """ @@ -442,7 +448,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert len(users) == 1 def test_selectfirst(self): - """Query.selectfirst(arg=None, **kwargs) + r"""Query.selectfirst(arg=None, \**kwargs) bounced = session.query(Address).selectfirst( addresses_table.c.bounces > 0) @@ -457,7 +463,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert bounced.bounces > 0 def test_selectfirst_by(self): - """Query.selectfirst_by(*args, **params) + r"""Query.selectfirst_by(\*args, \**params) onebounce = session.query(Address).selectfirst_by(bounces=1) @@ -491,7 +497,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert onebounce_user.name == "jack" def test_selectone(self): - """Query.selectone(arg=None, **kwargs) + r"""Query.selectone(arg=None, \**kwargs) ed = session.query(User).selectone(users_table.c.name == 'ed') @@ -535,7 +541,7 @@ class QueryAlternativesTest(fixtures.MappedTest): ) def test_select_statement(self): - """Query.select_statement(statement, **params) + r"""Query.select_statement(statement, \**params) users = session.query(User).select_statement(users_table.select()) @@ -549,7 +555,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert len(users) == 4 def test_select_text(self): - """Query.select_text(text, **params) + r"""Query.select_text(text, \**params) users = session.query(User).select_text('SELECT * FROM users_table') @@ -567,7 +573,7 @@ class QueryAlternativesTest(fixtures.MappedTest): assert len(users) == 4 def test_select_whereclause(self): - """Query.select_whereclause(whereclause=None, params=None, **kwargs) + r"""Query.select_whereclause(whereclause=None, params=None, \**kwargs) users = session,query(User).select_whereclause(users.c.name=='ed') diff --git a/test/orm/test_expire.py b/test/orm/test_expire.py index f688ca9dd..03ef7b03a 100644 --- a/test/orm/test_expire.py +++ b/test/orm/test_expire.py @@ -1397,7 +1397,7 @@ class PolymorphicExpireTest(fixtures.MappedTest): sess.add(e1) assert e1.name == "engineer1" - def test_no_instance_key(self): + def test_no_instance_key_pk_absent(self): Engineer = self.classes.Engineer # same as test_no_instance_key, but the PK columns diff --git a/test/orm/test_generative.py b/test/orm/test_generative.py index 1b7b99ee4..abc666af1 100644 --- a/test/orm/test_generative.py +++ b/test/orm/test_generative.py @@ -158,7 +158,7 @@ class GenerativeQueryTest(fixtures.MappedTest): assert query.order_by(Foo.bar)[0].bar == 0 assert query.order_by(sa.desc(Foo.bar))[0].bar == 99 - def test_offset(self): + def test_offset_order_by(self): Foo = self.classes.Foo query = create_session().query(Foo) diff --git a/test/orm/test_versioning.py b/test/orm/test_versioning.py index b70430390..e54925f0b 100644 --- a/test/orm/test_versioning.py +++ b/test/orm/test_versioning.py @@ -1260,7 +1260,7 @@ class ServerVersioningTest(fixtures.MappedTest): pass @compiles(IncDefault) - def compile(element, compiler, **kw): + def compile_(element, compiler, **kw): # cache the counter value on the statement # itself so the assertsql system gets the same # value when it compiles the statement a second time diff --git a/test/sql/test_cte.py b/test/sql/test_cte.py index af66beb6d..ed2787b0f 100644 --- a/test/sql/test_cte.py +++ b/test/sql/test_cte.py @@ -245,7 +245,7 @@ class CTETest(fixtures.TestBase, AssertsCompiledSQL): def test_recursive_union_no_alias_two(self): """ - pg's example: + pg's example:: WITH RECURSIVE t(n) AS ( VALUES (1) diff --git a/test/sql/test_operators.py b/test/sql/test_operators.py index 304e16681..978d3101d 100644 --- a/test/sql/test_operators.py +++ b/test/sql/test_operators.py @@ -609,10 +609,10 @@ class ExtensionOperatorTest(fixtures.TestBase, testing.AssertsCompiledSQL): class JSONIndexOpTest(fixtures.TestBase, testing.AssertsCompiledSQL): def setUp(self): class MyTypeCompiler(compiler.GenericTypeCompiler): - def visit_mytype(self, type, **kw): + def visit_mytype(self, type_, **kw): return "MYTYPE" - def visit_myothertype(self, type, **kw): + def visit_myothertype(self, type_, **kw): return "MYOTHERTYPE" class MyCompiler(compiler.SQLCompiler): @@ -726,10 +726,10 @@ class JSONIndexOpTest(fixtures.TestBase, testing.AssertsCompiledSQL): class ArrayIndexOpTest(fixtures.TestBase, testing.AssertsCompiledSQL): def setUp(self): class MyTypeCompiler(compiler.GenericTypeCompiler): - def visit_mytype(self, type, **kw): + def visit_mytype(self, type_, **kw): return "MYTYPE" - def visit_myothertype(self, type, **kw): + def visit_myothertype(self, type_, **kw): return "MYOTHERTYPE" class MyCompiler(compiler.SQLCompiler): diff --git a/test/sql/test_quote.py b/test/sql/test_quote.py index f7a04eae7..49dfbba9f 100644 --- a/test/sql/test_quote.py +++ b/test/sql/test_quote.py @@ -217,18 +217,18 @@ class QuoteTest(fixtures.TestBase, AssertsCompiledSQL): """test the quoting of labels. If labels aren't quoted, a query in postgresql in particular will - fail since it produces: - - SELECT - LaLa.lowercase, LaLa."UPPERCASE", LaLa."MixedCase", LaLa."ASC" - FROM ( - SELECT DISTINCT - "WorstCase1".lowercase AS lowercase, - "WorstCase1"."UPPERCASE" AS UPPERCASE, - "WorstCase1"."MixedCase" AS MixedCase, - "WorstCase1"."ASC" AS ASC - FROM "WorstCase1" - ) AS LaLa + fail since it produces:: + + SELECT + LaLa.lowercase, LaLa."UPPERCASE", LaLa."MixedCase", LaLa."ASC" + FROM ( + SELECT DISTINCT + "WorstCase1".lowercase AS lowercase, + "WorstCase1"."UPPERCASE" AS UPPERCASE, + "WorstCase1"."MixedCase" AS MixedCase, + "WorstCase1"."ASC" AS ASC + FROM "WorstCase1" + ) AS LaLa where the "UPPERCASE" column of "LaLa" doesn't exist. """ |