summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2013-04-27 19:53:57 -0400
committerMike Bayer <mike_mp@zzzcomputing.com>2013-04-27 19:53:57 -0400
commit4b614b9b35cd2baddb7ca67c04bee5d70ec6a172 (patch)
tree7483cd269f5823f903f96709eb864fff9b6d9383 /examples
parent9716a5c45e6185c5871555722d8495880f0e8c7a (diff)
downloadsqlalchemy-4b614b9b35cd2baddb7ca67c04bee5d70ec6a172.tar.gz
- the raw 2to3 run
- went through examples/ and cleaned out excess list() calls
Diffstat (limited to 'examples')
-rw-r--r--examples/adjacency_list/adjacency_list.py6
-rw-r--r--examples/association/basic_association.py6
-rw-r--r--examples/association/dict_of_sets_with_default.py4
-rw-r--r--examples/association/proxied_association.py10
-rw-r--r--examples/custom_attributes/listen_for_events.py2
-rw-r--r--examples/dogpile_caching/advanced.py34
-rw-r--r--examples/dogpile_caching/caching_query.py4
-rw-r--r--examples/dogpile_caching/environment.py6
-rw-r--r--examples/dogpile_caching/fixture_data.py6
-rw-r--r--examples/dogpile_caching/helloworld.py18
-rw-r--r--examples/dogpile_caching/local_session_caching.py6
-rw-r--r--examples/dogpile_caching/model.py4
-rw-r--r--examples/dogpile_caching/relation_caching.py10
-rw-r--r--examples/dynamic_dict/dynamic_dict.py176
-rw-r--r--examples/elementtree/adjacency_list.py40
-rw-r--r--examples/elementtree/optimized_al.py42
-rw-r--r--examples/generic_associations/discriminator_on_association.py4
-rw-r--r--examples/generic_associations/table_per_association.py2
-rw-r--r--examples/generic_associations/table_per_related.py4
-rw-r--r--examples/inheritance/concrete.py2
-rw-r--r--examples/inheritance/joined.py14
-rw-r--r--examples/inheritance/single.py10
-rw-r--r--examples/large_collection/large_collection.py16
-rw-r--r--examples/postgis/postgis.py2
-rw-r--r--examples/versioning/_lib.py2
-rw-r--r--examples/versioning/history_meta.py2
-rw-r--r--examples/versioning/test_versioning.py36
-rw-r--r--examples/vertical/dictlike-polymorphic.py66
-rw-r--r--examples/vertical/dictlike.py58
29 files changed, 296 insertions, 296 deletions
diff --git a/examples/adjacency_list/adjacency_list.py b/examples/adjacency_list/adjacency_list.py
index 1020cc57d..a0683ea0c 100644
--- a/examples/adjacency_list/adjacency_list.py
+++ b/examples/adjacency_list/adjacency_list.py
@@ -55,9 +55,9 @@ if __name__ == '__main__':
def msg(msg, *args):
msg = msg % args
- print "\n\n\n" + "-" * len(msg.split("\n")[0])
- print msg
- print "-" * len(msg.split("\n")[0])
+ print("\n\n\n" + "-" * len(msg.split("\n")[0]))
+ print(msg)
+ print("-" * len(msg.split("\n")[0]))
msg("Creating Tree Table:")
diff --git a/examples/association/basic_association.py b/examples/association/basic_association.py
index 29a473fce..a175b1b89 100644
--- a/examples/association/basic_association.py
+++ b/examples/association/basic_association.py
@@ -83,12 +83,12 @@ if __name__ == '__main__':
# query the order, print items
order = session.query(Order).filter_by(customer_name='john smith').one()
- print [(order_item.item.description, order_item.price)
- for order_item in order.order_items]
+ print([(order_item.item.description, order_item.price)
+ for order_item in order.order_items])
# print customers who bought 'MySQL Crowbar' on sale
q = session.query(Order).join('order_items', 'item')
q = q.filter(and_(Item.description == 'MySQL Crowbar',
Item.price > OrderItem.price))
- print [order.customer_name for order in q]
+ print([order.customer_name for order in q])
diff --git a/examples/association/dict_of_sets_with_default.py b/examples/association/dict_of_sets_with_default.py
index 9a43e300c..f541727e7 100644
--- a/examples/association/dict_of_sets_with_default.py
+++ b/examples/association/dict_of_sets_with_default.py
@@ -75,13 +75,13 @@ if __name__ == '__main__':
session.commit()
a1 = session.query(A).first()
- print a1.collections["1"]
+ print(a1.collections["1"])
a1.collections["1"].add(4)
session.commit()
a1.collections["2"].update([7, 8, 9])
session.commit()
- print a1.collections["2"]
+ print(a1.collections["2"])
diff --git a/examples/association/proxied_association.py b/examples/association/proxied_association.py
index 7f4d611a7..4cf1c51be 100644
--- a/examples/association/proxied_association.py
+++ b/examples/association/proxied_association.py
@@ -86,16 +86,16 @@ if __name__ == '__main__':
order = session.query(Order).filter_by(customer_name='john smith').one()
# print items based on the OrderItem collection directly
- print [(assoc.item.description, assoc.price, assoc.item.price)
- for assoc in order.order_items]
+ print([(assoc.item.description, assoc.price, assoc.item.price)
+ for assoc in order.order_items])
# print items based on the "proxied" items collection
- print [(item.description, item.price)
- for item in order.items]
+ print([(item.description, item.price)
+ for item in order.items])
# print customers who bought 'MySQL Crowbar' on sale
orders = session.query(Order).\
join('order_items', 'item').\
filter(Item.description == 'MySQL Crowbar').\
filter(Item.price > OrderItem.price)
- print [o.customer_name for o in orders]
+ print([o.customer_name for o in orders])
diff --git a/examples/custom_attributes/listen_for_events.py b/examples/custom_attributes/listen_for_events.py
index 4cdf4b056..82bc860fa 100644
--- a/examples/custom_attributes/listen_for_events.py
+++ b/examples/custom_attributes/listen_for_events.py
@@ -34,7 +34,7 @@ if __name__ == '__main__':
if oldvalue:
s += "which replaced the value '%s', " % oldvalue
s += "on object %s" % self
- print s
+ print(s)
Base = declarative_base(cls=Base)
diff --git a/examples/dogpile_caching/advanced.py b/examples/dogpile_caching/advanced.py
index 6bfacfcf0..f1a18a4d7 100644
--- a/examples/dogpile_caching/advanced.py
+++ b/examples/dogpile_caching/advanced.py
@@ -6,9 +6,9 @@ and collection caching.
"""
-from environment import Session
-from model import Person, Address, cache_address_bits
-from caching_query import FromCache, RelationshipCache
+from .environment import Session
+from .model import Person, Address, cache_address_bits
+from .caching_query import FromCache, RelationshipCache
from sqlalchemy.orm import joinedload
def load_name_range(start, end, invalidate=False):
@@ -49,31 +49,31 @@ def load_name_range(start, end, invalidate=False):
return q.all()
-print "two through twelve, possibly from cache:\n"
-print ", ".join([p.name for p in load_name_range(2, 12)])
+print("two through twelve, possibly from cache:\n")
+print(", ".join([p.name for p in load_name_range(2, 12)]))
-print "\ntwenty five through forty, possibly from cache:\n"
-print ", ".join([p.name for p in load_name_range(25, 40)])
+print("\ntwenty five through forty, possibly from cache:\n")
+print(", ".join([p.name for p in load_name_range(25, 40)]))
# loading them again, no SQL is emitted
-print "\ntwo through twelve, from the cache:\n"
-print ", ".join([p.name for p in load_name_range(2, 12)])
+print("\ntwo through twelve, from the cache:\n")
+print(", ".join([p.name for p in load_name_range(2, 12)]))
# but with invalidate, they are
-print "\ntwenty five through forty, invalidate first:\n"
-print ", ".join([p.name for p in load_name_range(25, 40, True)])
+print("\ntwenty five through forty, invalidate first:\n")
+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"
+print("\n\nPeople plus addresses, two through twelve, addresses possibly from cache")
for p in load_name_range(2, 12):
- print p.format_full()
+ print(p.format_full())
# illustrate the address loading from either cache/already
# on the Person
-print "\n\nPeople plus addresses, two through twelve, addresses from cache"
+print("\n\nPeople plus addresses, two through twelve, addresses from cache")
for p in load_name_range(2, 12):
- print p.format_full()
+ print(p.format_full())
-print "\n\nIf this was the first run of advanced.py, try "\
- "a second run. Only one SQL statement will be emitted."
+print("\n\nIf this was the first run of advanced.py, try "\
+ "a second run. Only one SQL statement will be emitted.")
diff --git a/examples/dogpile_caching/caching_query.py b/examples/dogpile_caching/caching_query.py
index f4724fb0b..18eb2b908 100644
--- a/examples/dogpile_caching/caching_query.py
+++ b/examples/dogpile_caching/caching_query.py
@@ -143,8 +143,8 @@ def _key_from_query(query, qualifier=None):
# here we return the key as a long string. our "key mangler"
# set up with the region will boil it down to an md5.
return " ".join(
- [unicode(compiled)] +
- [unicode(params[k]) for k in sorted(params)])
+ [str(compiled)] +
+ [str(params[k]) for k in sorted(params)])
class FromCache(MapperOption):
"""Specifies that a Query should load results from a cache."""
diff --git a/examples/dogpile_caching/environment.py b/examples/dogpile_caching/environment.py
index f210d26ac..36b9585b2 100644
--- a/examples/dogpile_caching/environment.py
+++ b/examples/dogpile_caching/environment.py
@@ -4,7 +4,7 @@ Establish data / cache file paths, and configurations,
bootstrap fixture data if necessary.
"""
-import caching_query
+from . import caching_query
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
@@ -31,7 +31,7 @@ Base = declarative_base()
root = "./dogpile_data/"
if not os.path.exists(root):
- raw_input("Will create datafiles in %r.\n"
+ input("Will create datafiles in %r.\n"
"To reset the cache + database, delete this directory.\n"
"Press enter to continue.\n" % root
)
@@ -77,7 +77,7 @@ installed = False
def bootstrap():
global installed
- import fixture_data
+ from . import fixture_data
if not os.path.exists(dbfile):
fixture_data.install()
installed = True \ No newline at end of file
diff --git a/examples/dogpile_caching/fixture_data.py b/examples/dogpile_caching/fixture_data.py
index 1db75ea05..f93f32fd9 100644
--- a/examples/dogpile_caching/fixture_data.py
+++ b/examples/dogpile_caching/fixture_data.py
@@ -5,8 +5,8 @@ Canadian cities. Then, 100 Person records are installed, each with a
randomly selected postal code.
"""
-from environment import Session, Base
-from model import City, Country, PostalCode, Person, Address
+from .environment import Session, Base
+from .model import City, Country, PostalCode, Person, Address
import random
def install():
@@ -35,7 +35,7 @@ def install():
Session.add_all(pc)
all_post_codes.extend(pc)
- for i in xrange(1, 51):
+ for i in range(1, 51):
person = Person(
"person %.2d" % i,
Address(
diff --git a/examples/dogpile_caching/helloworld.py b/examples/dogpile_caching/helloworld.py
index e2e4d4f78..4561097b6 100644
--- a/examples/dogpile_caching/helloworld.py
+++ b/examples/dogpile_caching/helloworld.py
@@ -4,12 +4,12 @@ Illustrate how to load some data, and cache the results.
"""
-from environment import Session
-from model import Person
-from caching_query import FromCache
+from .environment import Session
+from .model import Person
+from .caching_query import FromCache
# load Person objects. cache the result under the namespace "all_people".
-print "loading people...."
+print("loading people....")
people = Session.query(Person).options(FromCache("default")).all()
# remove the Session. next query starts from scratch.
@@ -17,12 +17,12 @@ Session.remove()
# load again, using the same FromCache option. now they're cached
# under "all_people", no SQL is emitted.
-print "loading people....again!"
+print("loading people....again!")
people = Session.query(Person).options(FromCache("default")).all()
# want to load on some different kind of query ? change the namespace
# you send to FromCache
-print "loading people two through twelve"
+print("loading people two through twelve")
people_two_through_twelve = Session.query(Person).\
options(FromCache("default")).\
filter(Person.name.between("person 02", "person 12")).\
@@ -32,7 +32,7 @@ people_two_through_twelve = Session.query(Person).\
# the bind parameters of the query. So this query, having
# different literal parameters under "Person.name.between()" than the
# previous one, issues new SQL...
-print "loading people five through fifteen"
+print("loading people five through fifteen")
people_five_through_fifteen = Session.query(Person).\
options(FromCache("default")).\
filter(Person.name.between("person 05", "person 15")).\
@@ -40,7 +40,7 @@ people_five_through_fifteen = Session.query(Person).\
# ... but using the same params as are already cached, no SQL
-print "loading people two through twelve...again!"
+print("loading people two through twelve...again!")
people_two_through_twelve = Session.query(Person).\
options(FromCache("default")).\
filter(Person.name.between("person 02", "person 12")).\
@@ -51,7 +51,7 @@ people_two_through_twelve = Session.query(Person).\
# each Query, which includes at the very least the same FromCache,
# same list of objects to be loaded, and the same parameters in the
# same order, then call invalidate().
-print "invalidating everything"
+print("invalidating everything")
Session.query(Person).options(FromCache("default")).invalidate()
Session.query(Person).\
options(FromCache("default")).\
diff --git a/examples/dogpile_caching/local_session_caching.py b/examples/dogpile_caching/local_session_caching.py
index 383b31c11..cf0083d2e 100644
--- a/examples/dogpile_caching/local_session_caching.py
+++ b/examples/dogpile_caching/local_session_caching.py
@@ -53,8 +53,8 @@ register_backend("sqlalchemy.session", __name__, "ScopedSessionBackend")
if __name__ == '__main__':
- from environment import Session, regions
- from caching_query import FromCache
+ from .environment import Session, regions
+ from .caching_query import FromCache
from dogpile.cache import make_region
# set up a region based on the ScopedSessionBackend,
@@ -67,7 +67,7 @@ if __name__ == '__main__':
}
)
- from model import Person
+ from .model import Person
# query to load Person by name, with criterion
# of "person 10"
diff --git a/examples/dogpile_caching/model.py b/examples/dogpile_caching/model.py
index 6f1cffedf..622d31e6a 100644
--- a/examples/dogpile_caching/model.py
+++ b/examples/dogpile_caching/model.py
@@ -10,8 +10,8 @@ City --(has a)--> Country
"""
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
-from caching_query import FromCache, RelationshipCache
-from environment import Base, bootstrap
+from .caching_query import FromCache, RelationshipCache
+from .environment import Base, bootstrap
class Country(Base):
__tablename__ = 'country'
diff --git a/examples/dogpile_caching/relation_caching.py b/examples/dogpile_caching/relation_caching.py
index 7a5779620..d40752e48 100644
--- a/examples/dogpile_caching/relation_caching.py
+++ b/examples/dogpile_caching/relation_caching.py
@@ -5,16 +5,16 @@ related PostalCode, City, Country objects should be pulled from long
term cache.
"""
-from environment import Session, root
-from model import Person, cache_address_bits
+from .environment import Session, root
+from .model import Person, cache_address_bits
from sqlalchemy.orm import joinedload
import os
for p in Session.query(Person).options(joinedload(Person.addresses), cache_address_bits):
- print p.format_full()
+ print(p.format_full())
-print "\n\nIf this was the first run of relationship_caching.py, SQL was likely emitted to "\
+print("\n\nIf this was the first run of relationship_caching.py, SQL was likely emitted to "\
"load postal codes, cities, countries.\n"\
"If run a second time, assuming the cache is still valid, "\
"only a single SQL statement will run - all "\
@@ -22,4 +22,4 @@ print "\n\nIf this was the first run of relationship_caching.py, SQL was likely
"To clear the cache, delete the file %r. \n"\
"This will cause a re-load of cities, postal codes and countries on "\
"the next run.\n"\
- % os.path.join(root, 'cache.dbm')
+ % os.path.join(root, 'cache.dbm'))
diff --git a/examples/dynamic_dict/dynamic_dict.py b/examples/dynamic_dict/dynamic_dict.py
index ec7c8e918..530674f2e 100644
--- a/examples/dynamic_dict/dynamic_dict.py
+++ b/examples/dynamic_dict/dynamic_dict.py
@@ -1,88 +1,88 @@
-class ProxyDict(object):
- def __init__(self, parent, collection_name, childclass, keyname):
- self.parent = parent
- self.collection_name = collection_name
- self.childclass = childclass
- self.keyname = keyname
-
- @property
- def collection(self):
- return getattr(self.parent, self.collection_name)
-
- def keys(self):
- descriptor = getattr(self.childclass, self.keyname)
- return [x[0] for x in self.collection.values(descriptor)]
-
- def __getitem__(self, key):
- x = self.collection.filter_by(**{self.keyname:key}).first()
- if x:
- return x
- else:
- raise KeyError(key)
-
- def __setitem__(self, key, value):
- try:
- existing = self[key]
- self.collection.remove(existing)
- except KeyError:
- pass
- self.collection.append(value)
-
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
-from sqlalchemy.orm import sessionmaker, relationship
-
-engine = create_engine('sqlite://', echo=True)
-Base = declarative_base(engine)
-
-class Parent(Base):
- __tablename__ = 'parent'
- id = Column(Integer, primary_key=True)
- name = Column(String(50))
- _collection = relationship("Child", lazy="dynamic",
- cascade="all, delete-orphan")
-
- @property
- def child_map(self):
- return ProxyDict(self, '_collection', Child, 'key')
-
-class Child(Base):
- __tablename__ = 'child'
- id = Column(Integer, primary_key=True)
- key = Column(String(50))
- parent_id = Column(Integer, ForeignKey('parent.id'))
-
- def __repr__(self):
- return "Child(key=%r)" % self.key
-
-Base.metadata.create_all()
-
-sess = sessionmaker()()
-
-p1 = Parent(name='p1')
-sess.add(p1)
-
-print "\n---------begin setting nodes, autoflush occurs\n"
-p1.child_map['k1'] = Child(key='k1')
-p1.child_map['k2'] = Child(key='k2')
-
-# this will autoflush the current map.
-# ['k1', 'k2']
-print "\n---------print keys - flushes first\n"
-print p1.child_map.keys()
-
-# k1
-print "\n---------print 'k1' node\n"
-print p1.child_map['k1']
-
-print "\n---------update 'k2' node - must find existing, and replace\n"
-p1.child_map['k2'] = Child(key='k2')
-
-print "\n---------print 'k2' key - flushes first\n"
-# k2
-print p1.child_map['k2']
-
-print "\n---------print all child nodes\n"
-# [k1, k2b]
-print sess.query(Child).all()
-
+class ProxyDict(object):
+ def __init__(self, parent, collection_name, childclass, keyname):
+ self.parent = parent
+ self.collection_name = collection_name
+ self.childclass = childclass
+ self.keyname = keyname
+
+ @property
+ def collection(self):
+ return getattr(self.parent, self.collection_name)
+
+ def keys(self):
+ descriptor = getattr(self.childclass, self.keyname)
+ return [x[0] for x in self.collection.values(descriptor)]
+
+ def __getitem__(self, key):
+ x = self.collection.filter_by(**{self.keyname:key}).first()
+ if x:
+ return x
+ else:
+ raise KeyError(key)
+
+ def __setitem__(self, key, value):
+ try:
+ existing = self[key]
+ self.collection.remove(existing)
+ except KeyError:
+ pass
+ self.collection.append(value)
+
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
+from sqlalchemy.orm import sessionmaker, relationship
+
+engine = create_engine('sqlite://', echo=True)
+Base = declarative_base(engine)
+
+class Parent(Base):
+ __tablename__ = 'parent'
+ id = Column(Integer, primary_key=True)
+ name = Column(String(50))
+ _collection = relationship("Child", lazy="dynamic",
+ cascade="all, delete-orphan")
+
+ @property
+ def child_map(self):
+ return ProxyDict(self, '_collection', Child, 'key')
+
+class Child(Base):
+ __tablename__ = 'child'
+ id = Column(Integer, primary_key=True)
+ key = Column(String(50))
+ parent_id = Column(Integer, ForeignKey('parent.id'))
+
+ def __repr__(self):
+ return "Child(key=%r)" % self.key
+
+Base.metadata.create_all()
+
+sess = sessionmaker()()
+
+p1 = Parent(name='p1')
+sess.add(p1)
+
+print("\n---------begin setting nodes, autoflush occurs\n")
+p1.child_map['k1'] = Child(key='k1')
+p1.child_map['k2'] = Child(key='k2')
+
+# this will autoflush the current map.
+# ['k1', 'k2']
+print("\n---------print keys - flushes first\n")
+print(list(p1.child_map.keys()))
+
+# k1
+print("\n---------print 'k1' node\n")
+print(p1.child_map['k1'])
+
+print("\n---------update 'k2' node - must find existing, and replace\n")
+p1.child_map['k2'] = Child(key='k2')
+
+print("\n---------print 'k2' key - flushes first\n")
+# k2
+print(p1.child_map['k2'])
+
+print("\n---------print all child nodes\n")
+# [k1, k2b]
+print(sess.query(Child).all())
+
diff --git a/examples/elementtree/adjacency_list.py b/examples/elementtree/adjacency_list.py
index 3b9e4c523..a3ad42778 100644
--- a/examples/elementtree/adjacency_list.py
+++ b/examples/elementtree/adjacency_list.py
@@ -11,7 +11,7 @@ from sqlalchemy import (MetaData, Table, Column, Integer, String, ForeignKey,
Unicode, and_, create_engine)
from sqlalchemy.orm import mapper, relationship, Session, lazyload
-import sys, os, StringIO, re
+import sys, os, io, re
from xml.etree import ElementTree
@@ -56,7 +56,7 @@ class Document(object):
self.element = element
def __str__(self):
- buf = StringIO.StringIO()
+ buf = io.StringIO()
self.element.write(buf)
return buf.getvalue()
@@ -120,11 +120,11 @@ class ElementTreeMarshal(object):
def __set__(self, document, element):
def traverse(node):
n = _Node()
- n.tag = unicode(node.tag)
- n.text = unicode(node.text)
- n.tail = unicode(node.tail)
+ n.tag = str(node.tag)
+ n.text = str(node.text)
+ n.tail = str(node.tail)
n.children = [traverse(n2) for n2 in node]
- n.attributes = [_Attribute(unicode(k), unicode(v)) for k, v in node.attrib.iteritems()]
+ n.attributes = [_Attribute(str(k), str(v)) for k, v in node.attrib.items()]
return n
document._root = traverse(element.getroot())
@@ -150,23 +150,23 @@ for file in ('test.xml', 'test2.xml', 'test3.xml'):
doc = ElementTree.parse(filename)
session.add(Document(file, doc))
-print "\nSaving three documents...", line
+print("\nSaving three documents...", line)
session.commit()
-print "Done."
+print("Done.")
-print "\nFull text of document 'text.xml':", line
+print("\nFull text of document 'text.xml':", line)
document = session.query(Document).filter_by(filename="test.xml").first()
-print document
+print(document)
############################################ PART VI - Searching for Paths #########################
# manually search for a document which contains "/somefile/header/field1:hi"
-d = session.query(Document).join('_root', aliased=True).filter(_Node.tag==u'somefile').\
- join('children', aliased=True, from_joinpoint=True).filter(_Node.tag==u'header').\
+d = session.query(Document).join('_root', aliased=True).filter(_Node.tag=='somefile').\
+ join('children', aliased=True, from_joinpoint=True).filter(_Node.tag=='header').\
join('children', aliased=True, from_joinpoint=True).filter(
- and_(_Node.tag==u'field1', _Node.text==u'hi')).one()
-print d
+ and_(_Node.tag=='field1', _Node.text=='hi')).one()
+print(d)
# generalize the above approach into an extremely impoverished xpath function:
def find_document(path, compareto):
@@ -188,11 +188,11 @@ def find_document(path, compareto):
return query.options(lazyload('_root')).filter(_Node.text==compareto).all()
for path, compareto in (
- (u'/somefile/header/field1', u'hi'),
- (u'/somefile/field1', u'hi'),
- (u'/somefile/header/field2', u'there'),
- (u'/somefile/header/field2[@attr=foo]', u'there')
+ ('/somefile/header/field1', 'hi'),
+ ('/somefile/field1', 'hi'),
+ ('/somefile/header/field2', 'there'),
+ ('/somefile/header/field2[@attr=foo]', 'there')
):
- print "\nDocuments containing '%s=%s':" % (path, compareto), line
- print [d.filename for d in find_document(path, compareto)]
+ print("\nDocuments containing '%s=%s':" % (path, compareto), line)
+ print([d.filename for d in find_document(path, compareto)])
diff --git a/examples/elementtree/optimized_al.py b/examples/elementtree/optimized_al.py
index 1cec61366..1dbad0943 100644
--- a/examples/elementtree/optimized_al.py
+++ b/examples/elementtree/optimized_al.py
@@ -10,7 +10,7 @@ from sqlalchemy import (MetaData, Table, Column, Integer, String, ForeignKey,
Unicode, and_, create_engine)
from sqlalchemy.orm import mapper, relationship, Session, lazyload
-import sys, os, StringIO, re
+import sys, os, io, re
from xml.etree import ElementTree
@@ -55,7 +55,7 @@ class Document(object):
self.element = element
def __str__(self):
- buf = StringIO.StringIO()
+ buf = io.StringIO()
self.element.write(buf)
return buf.getvalue()
@@ -127,12 +127,12 @@ class ElementTreeMarshal(object):
def __set__(self, document, element):
def traverse(node):
n = _Node()
- n.tag = unicode(node.tag)
- n.text = unicode(node.text)
- n.tail = unicode(node.tail)
+ n.tag = str(node.tag)
+ n.text = str(node.text)
+ n.tail = str(node.tail)
document._nodes.append(n)
n.children = [traverse(n2) for n2 in node]
- n.attributes = [_Attribute(unicode(k), unicode(v)) for k, v in node.attrib.iteritems()]
+ n.attributes = [_Attribute(str(k), str(v)) for k, v in node.attrib.items()]
return n
traverse(element.getroot())
@@ -158,27 +158,27 @@ for file in ('test.xml', 'test2.xml', 'test3.xml'):
doc = ElementTree.parse(filename)
session.add(Document(file, doc))
-print "\nSaving three documents...", line
+print("\nSaving three documents...", line)
session.commit()
-print "Done."
+print("Done.")
-print "\nFull text of document 'text.xml':", line
+print("\nFull text of document 'text.xml':", line)
document = session.query(Document).filter_by(filename="test.xml").first()
-print document
+print(document)
######################## 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
+print("\nManual search for /somefile/header/field1=='hi':", line)
d = session.query(Document).join('_nodes', aliased=True).\
- filter(and_(_Node.parent_id==None, _Node.tag==u'somefile')).\
+ filter(and_(_Node.parent_id==None, _Node.tag=='somefile')).\
join('children', aliased=True, from_joinpoint=True).\
- filter(_Node.tag==u'header').\
+ filter(_Node.tag=='header').\
join('children', aliased=True, from_joinpoint=True).\
- filter(and_(_Node.tag==u'field1', _Node.text==u'hi')).\
+ filter(and_(_Node.tag=='field1', _Node.text=='hi')).\
one()
-print d
+print(d)
# generalize the above approach into an extremely impoverished xpath function:
def find_document(path, compareto):
@@ -203,11 +203,11 @@ def find_document(path, compareto):
return query.options(lazyload('_nodes')).filter(_Node.text==compareto).all()
for path, compareto in (
- (u'/somefile/header/field1', u'hi'),
- (u'/somefile/field1', u'hi'),
- (u'/somefile/header/field2', u'there'),
- (u'/somefile/header/field2[@attr=foo]', u'there')
+ ('/somefile/header/field1', 'hi'),
+ ('/somefile/field1', 'hi'),
+ ('/somefile/header/field2', 'there'),
+ ('/somefile/header/field2[@attr=foo]', 'there')
):
- print "\nDocuments containing '%s=%s':" % (path, compareto), line
- print [d.filename for d in find_document(path, compareto)]
+ print("\nDocuments containing '%s=%s':" % (path, compareto), line)
+ print([d.filename for d in find_document(path, compareto)])
diff --git a/examples/generic_associations/discriminator_on_association.py b/examples/generic_associations/discriminator_on_association.py
index 3c170d5c8..7b4565a85 100644
--- a/examples/generic_associations/discriminator_on_association.py
+++ b/examples/generic_associations/discriminator_on_association.py
@@ -144,5 +144,5 @@ session.commit()
for customer in session.query(Customer):
for address in customer.addresses:
- print address
- print address.parent \ No newline at end of file
+ print(address)
+ print(address.parent) \ No newline at end of file
diff --git a/examples/generic_associations/table_per_association.py b/examples/generic_associations/table_per_association.py
index e1ff2be5b..84e85de2f 100644
--- a/examples/generic_associations/table_per_association.py
+++ b/examples/generic_associations/table_per_association.py
@@ -102,5 +102,5 @@ session.commit()
for customer in session.query(Customer):
for address in customer.addresses:
- print address
+ print(address)
# no parent here \ No newline at end of file
diff --git a/examples/generic_associations/table_per_related.py b/examples/generic_associations/table_per_related.py
index 693908189..0ec5f29b0 100644
--- a/examples/generic_associations/table_per_related.py
+++ b/examples/generic_associations/table_per_related.py
@@ -103,5 +103,5 @@ session.commit()
for customer in session.query(Customer):
for address in customer.addresses:
- print address
- print address.parent \ No newline at end of file
+ print(address)
+ print(address.parent) \ No newline at end of file
diff --git a/examples/inheritance/concrete.py b/examples/inheritance/concrete.py
index 75741df6d..b05afa5ea 100644
--- a/examples/inheritance/concrete.py
+++ b/examples/inheritance/concrete.py
@@ -68,5 +68,5 @@ session.add(e1)
session.add(e2)
session.commit()
-print session.query(Employee).all()
+print(session.query(Employee).all())
diff --git a/examples/inheritance/joined.py b/examples/inheritance/joined.py
index 4d3dc08d0..c6ce37146 100644
--- a/examples/inheritance/joined.py
+++ b/examples/inheritance/joined.py
@@ -92,10 +92,10 @@ session.commit()
c = session.query(Company).get(1)
for e in c.employees:
- print e, inspect(e).key, e.company
+ print(e, inspect(e).key, e.company)
assert set([e.name for e in c.employees]) == set(['pointy haired boss',
'dilbert', 'joesmith', 'wally', 'jsmith'])
-print "\n"
+print("\n")
dilbert = session.query(Person).filter_by(name='dilbert').one()
dilbert2 = session.query(Engineer).filter_by(name='dilbert').one()
@@ -107,29 +107,29 @@ session.commit()
c = session.query(Company).get(1)
for e in c.employees:
- print e
+ print(e)
# query using with_polymorphic.
eng_manager = with_polymorphic(Person, [Engineer, Manager], aliased=True)
-print session.query(eng_manager).\
+print(session.query(eng_manager).\
filter(
or_(eng_manager.Engineer.engineer_name=='engineer1',
eng_manager.Manager.manager_name=='manager2'
)
- ).all()
+ ).all())
# illustrate join from Company,
# We use aliased=True
# to help when the selectable is used as the target of a join.
eng_manager = with_polymorphic(Person, [Engineer, Manager], aliased=True)
-print session.query(Company).\
+print(session.query(Company).\
join(
eng_manager,
Company.employees
).filter(
or_(eng_manager.Engineer.engineer_name=='engineer1',
eng_manager.Manager.manager_name=='manager2')
- ).all()
+ ).all())
session.commit()
diff --git a/examples/inheritance/single.py b/examples/inheritance/single.py
index b2f934120..b445f74a6 100644
--- a/examples/inheritance/single.py
+++ b/examples/inheritance/single.py
@@ -23,7 +23,7 @@ employees_table = Table('employees', metadata,
class Person(object):
def __init__(self, **kwargs):
- for key, value in kwargs.iteritems():
+ for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
return "Ordinary person %s" % self.name
@@ -39,7 +39,7 @@ class Manager(Person):
(self.name, self.status, self.manager_name)
class Company(object):
def __init__(self, **kwargs):
- for key, value in kwargs.iteritems():
+ for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
return "Company %s" % self.name
@@ -79,9 +79,9 @@ session.commit()
c = session.query(Company).get(1)
for e in c.employees:
- print e, e.company
+ print(e, e.company)
-print "\n"
+print("\n")
dilbert = session.query(Person).filter_by(name='dilbert').one()
dilbert2 = session.query(Engineer).filter_by(name='dilbert').one()
@@ -94,7 +94,7 @@ session.expunge_all()
c = session.query(Company).get(1)
for e in c.employees:
- print e
+ print(e)
session.delete(c)
session.commit()
diff --git a/examples/large_collection/large_collection.py b/examples/large_collection/large_collection.py
index 3e386ae64..82d2e554b 100644
--- a/examples/large_collection/large_collection.py
+++ b/examples/large_collection/large_collection.py
@@ -63,14 +63,14 @@ if __name__ == '__main__':
sess.add(org)
- print "-------------------------\nflush one - save org + 3 members\n"
+ print("-------------------------\nflush one - save org + 3 members\n")
sess.commit()
# the 'members' collection is a Query. it issues
# SQL as needed to load subsets of the collection.
- print "-------------------------\nload subset of members\n"
+ print("-------------------------\nload subset of members\n")
members = org.members.filter(member_table.c.name.like('%member t%')).all()
- print members
+ print(members)
# new Members can be appended without any
# SQL being emitted to load the full collection
@@ -78,19 +78,19 @@ if __name__ == '__main__':
org.members.append(Member('member five'))
org.members.append(Member('member six'))
- print "-------------------------\nflush two - save 3 more members\n"
+ print("-------------------------\nflush two - save 3 more members\n")
sess.commit()
# delete the object. Using ON DELETE CASCADE
# SQL is only emitted for the head row - the Member rows
# disappear automatically without the need for additional SQL.
sess.delete(org)
- print "-------------------------\nflush three - delete org, delete members in one statement\n"
+ print("-------------------------\nflush three - delete org, delete members in one statement\n")
sess.commit()
- print "-------------------------\nno Member rows should remain:\n"
- print sess.query(Member).count()
+ print("-------------------------\nno Member rows should remain:\n")
+ print(sess.query(Member).count())
sess.close()
- print "------------------------\ndone. dropping tables."
+ print("------------------------\ndone. dropping tables.")
meta.drop_all(engine) \ No newline at end of file
diff --git a/examples/postgis/postgis.py b/examples/postgis/postgis.py
index 0b86ad323..01671c5c4 100644
--- a/examples/postgis/postgis.py
+++ b/examples/postgis/postgis.py
@@ -251,7 +251,7 @@ if __name__ == '__main__':
road_table = Road.__table__
stmt = select([road_table]).where(road_table.c.road_geom.intersects(r1.road_geom))
- print session.execute(stmt).fetchall()
+ 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
diff --git a/examples/versioning/_lib.py b/examples/versioning/_lib.py
index ec0da4709..9132f9b35 100644
--- a/examples/versioning/_lib.py
+++ b/examples/versioning/_lib.py
@@ -17,7 +17,7 @@ def eq_(a, b, msg=None):
_repr_stack = set()
class BasicEntity(object):
def __init__(self, **kw):
- for key, value in kw.iteritems():
+ for key, value in kw.items():
setattr(self, key, value)
def __repr__(self):
diff --git a/examples/versioning/history_meta.py b/examples/versioning/history_meta.py
index 533599394..45f1c8369 100644
--- a/examples/versioning/history_meta.py
+++ b/examples/versioning/history_meta.py
@@ -166,7 +166,7 @@ def create_version(obj, session, deleted = False):
attr['version'] = obj.version
hist = history_cls()
- for key, value in attr.iteritems():
+ for key, value in attr.items():
setattr(hist, key, value)
session.add(hist)
obj.version += 1
diff --git a/examples/versioning/test_versioning.py b/examples/versioning/test_versioning.py
index 43e2b0ae1..5b57ecaa2 100644
--- a/examples/versioning/test_versioning.py
+++ b/examples/versioning/test_versioning.py
@@ -1,9 +1,9 @@
from unittest import TestCase
from sqlalchemy.ext.declarative import declarative_base
-from history_meta import Versioned, versioned_session
+from .history_meta import Versioned, versioned_session
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import clear_mappers, sessionmaker, deferred, relationship
-from _lib import ComparableEntity, eq_
+from ._lib import ComparableEntity, eq_
engine = Session = None
@@ -188,9 +188,9 @@ class TestVersioning(TestCase):
eq_(
sess.query(BaseClassHistory).order_by(BaseClassHistory.id).all(),
[
- SubClassSeparatePkHistory(id=1, name=u'sep1', type=u'sep', version=1),
- BaseClassHistory(id=2, name=u'base1', type=u'base', version=1),
- SubClassSamePkHistory(id=3, name=u'same1', type=u'same', version=1)
+ SubClassSeparatePkHistory(id=1, name='sep1', type='sep', version=1),
+ BaseClassHistory(id=2, name='base1', type='base', version=1),
+ SubClassSamePkHistory(id=3, name='same1', type='same', version=1)
]
)
@@ -199,10 +199,10 @@ class TestVersioning(TestCase):
eq_(
sess.query(BaseClassHistory).order_by(BaseClassHistory.id, BaseClassHistory.version).all(),
[
- SubClassSeparatePkHistory(id=1, name=u'sep1', type=u'sep', version=1),
- BaseClassHistory(id=2, name=u'base1', type=u'base', version=1),
- SubClassSamePkHistory(id=3, name=u'same1', type=u'same', version=1),
- SubClassSamePkHistory(id=3, name=u'same1', type=u'same', version=2)
+ SubClassSeparatePkHistory(id=1, name='sep1', type='sep', version=1),
+ BaseClassHistory(id=2, name='base1', type='base', version=1),
+ SubClassSamePkHistory(id=3, name='same1', type='same', version=1),
+ SubClassSamePkHistory(id=3, name='same1', type='same', version=2)
]
)
@@ -210,11 +210,11 @@ class TestVersioning(TestCase):
eq_(
sess.query(BaseClassHistory).order_by(BaseClassHistory.id, BaseClassHistory.version).all(),
[
- SubClassSeparatePkHistory(id=1, name=u'sep1', type=u'sep', version=1),
- BaseClassHistory(id=2, name=u'base1', type=u'base', version=1),
- BaseClassHistory(id=2, name=u'base1mod', type=u'base', version=2),
- SubClassSamePkHistory(id=3, name=u'same1', type=u'same', version=1),
- SubClassSamePkHistory(id=3, name=u'same1', type=u'same', version=2)
+ SubClassSeparatePkHistory(id=1, name='sep1', type='sep', version=1),
+ BaseClassHistory(id=2, name='base1', type='base', version=1),
+ BaseClassHistory(id=2, name='base1mod', type='base', version=2),
+ SubClassSamePkHistory(id=3, name='same1', type='same', version=1),
+ SubClassSamePkHistory(id=3, name='same1', type='same', version=2)
]
)
@@ -249,7 +249,7 @@ class TestVersioning(TestCase):
eq_(
sess.query(BaseClassHistory).order_by(BaseClassHistory.id, BaseClassHistory.version).all(),
- [BaseClassHistory(id=1, name=u'b1', type=u'base', version=1)]
+ [BaseClassHistory(id=1, name='b1', type='base', version=1)]
)
sc.name ='s1modified'
@@ -258,9 +258,9 @@ class TestVersioning(TestCase):
eq_(
sess.query(BaseClassHistory).order_by(BaseClassHistory.id, BaseClassHistory.version).all(),
[
- BaseClassHistory(id=1, name=u'b1', type=u'base', version=1),
- BaseClassHistory(id=1, name=u'b1modified', type=u'base', version=2),
- SubClassHistory(id=2, name=u's1', type=u'sub', version=1)
+ BaseClassHistory(id=1, name='b1', type='base', version=1),
+ BaseClassHistory(id=1, name='b1modified', type='base', version=2),
+ SubClassHistory(id=2, name='s1', type='sub', version=1)
]
)
diff --git a/examples/vertical/dictlike-polymorphic.py b/examples/vertical/dictlike-polymorphic.py
index f800eea73..872a7c52e 100644
--- a/examples/vertical/dictlike-polymorphic.py
+++ b/examples/vertical/dictlike-polymorphic.py
@@ -33,7 +33,7 @@ from sqlalchemy.orm import comparable_property
from sqlalchemy.ext.hybrid import hybrid_property
# Using the VerticalPropertyDictMixin from the base example
-from dictlike import VerticalPropertyDictMixin
+from .dictlike import VerticalPropertyDictMixin
class PolymorphicVerticalProperty(object):
"""A key/value pair with polymorphic value storage.
@@ -150,9 +150,9 @@ if __name__ == '__main__':
class AnimalFact(PolymorphicVerticalProperty):
type_map = {
- int: (u'integer', 'int_value'),
- unicode: (u'char', 'char_value'),
- bool: (u'boolean', 'boolean_value'),
+ int: ('integer', 'int_value'),
+ str: ('char', 'char_value'),
+ bool: ('boolean', 'boolean_value'),
type(None): (None, None),
}
@@ -190,42 +190,42 @@ if __name__ == '__main__':
metadata.create_all(engine)
session = Session(engine)
- stoat = Animal(u'stoat')
- stoat[u'color'] = u'red'
- stoat[u'cuteness'] = 7
- stoat[u'weasel-like'] = True
+ stoat = Animal('stoat')
+ stoat['color'] = 'red'
+ stoat['cuteness'] = 7
+ stoat['weasel-like'] = True
session.add(stoat)
session.commit()
- critter = session.query(Animal).filter(Animal.name == u'stoat').one()
- print critter[u'color']
- print critter[u'cuteness']
+ critter = session.query(Animal).filter(Animal.name == 'stoat').one()
+ print(critter['color'])
+ print(critter['cuteness'])
- print "changing cuteness value and type:"
- critter[u'cuteness'] = u'very cute'
+ print("changing cuteness value and type:")
+ critter['cuteness'] = 'very cute'
session.commit()
- marten = Animal(u'marten')
- marten[u'cuteness'] = 5
- marten[u'weasel-like'] = True
- marten[u'poisonous'] = False
+ marten = Animal('marten')
+ marten['cuteness'] = 5
+ marten['weasel-like'] = True
+ marten['poisonous'] = False
session.add(marten)
- shrew = Animal(u'shrew')
- shrew[u'cuteness'] = 5
- shrew[u'weasel-like'] = False
- shrew[u'poisonous'] = True
+ shrew = Animal('shrew')
+ shrew['cuteness'] = 5
+ shrew['weasel-like'] = False
+ shrew['poisonous'] = True
session.add(shrew)
session.commit()
q = (session.query(Animal).
filter(Animal.facts.any(
- and_(AnimalFact.key == u'weasel-like',
+ and_(AnimalFact.key == 'weasel-like',
AnimalFact.value == True))))
- print 'weasel-like animals', q.all()
+ print('weasel-like animals', q.all())
# Save some typing by wrapping that up in a function:
with_characteristic = lambda key, value: and_(AnimalFact.key == key,
@@ -233,24 +233,24 @@ if __name__ == '__main__':
q = (session.query(Animal).
filter(Animal.facts.any(
- with_characteristic(u'weasel-like', True))))
- print 'weasel-like animals again', q.all()
+ with_characteristic('weasel-like', True))))
+ print('weasel-like animals again', q.all())
q = (session.query(Animal).
- filter(Animal.facts.any(with_characteristic(u'poisonous', False))))
- print 'animals with poisonous=False', q.all()
+ filter(Animal.facts.any(with_characteristic('poisonous', False))))
+ print('animals with poisonous=False', q.all())
q = (session.query(Animal).
filter(or_(Animal.facts.any(
- with_characteristic(u'poisonous', False)),
- not_(Animal.facts.any(AnimalFact.key == u'poisonous')))))
- print 'non-poisonous animals', q.all()
+ with_characteristic('poisonous', False)),
+ not_(Animal.facts.any(AnimalFact.key == 'poisonous')))))
+ print('non-poisonous animals', q.all())
q = (session.query(Animal).
filter(Animal.facts.any(AnimalFact.value == 5)))
- print 'any animal with a .value of 5', q.all()
+ print('any animal with a .value of 5', q.all())
# Facts can be queried as well.
q = (session.query(AnimalFact).
- filter(with_characteristic(u'cuteness', u'very cute')))
- print q.all()
+ filter(with_characteristic('cuteness', 'very cute')))
+ print(q.all())
diff --git a/examples/vertical/dictlike.py b/examples/vertical/dictlike.py
index 71ab77342..f17d1acc8 100644
--- a/examples/vertical/dictlike.py
+++ b/examples/vertical/dictlike.py
@@ -176,49 +176,49 @@ if __name__ == '__main__':
metadata.create_all(engine)
session = Session(bind=engine)
- stoat = Animal(u'stoat')
- stoat[u'color'] = u'reddish'
- stoat[u'cuteness'] = u'somewhat'
+ stoat = Animal('stoat')
+ stoat['color'] = 'reddish'
+ stoat['cuteness'] = 'somewhat'
# dict-like assignment transparently creates entries in the
# stoat.facts collection:
- print stoat.facts[u'color']
+ print(stoat.facts['color'])
session.add(stoat)
session.commit()
- critter = session.query(Animal).filter(Animal.name == u'stoat').one()
- print critter[u'color']
- print critter[u'cuteness']
+ critter = session.query(Animal).filter(Animal.name == 'stoat').one()
+ print(critter['color'])
+ print(critter['cuteness'])
- critter[u'cuteness'] = u'very'
+ critter['cuteness'] = 'very'
- print 'changing cuteness:'
+ print('changing cuteness:')
engine.echo = True
session.commit()
engine.echo = False
- marten = Animal(u'marten')
- marten[u'color'] = u'brown'
- marten[u'cuteness'] = u'somewhat'
+ marten = Animal('marten')
+ marten['color'] = 'brown'
+ marten['cuteness'] = 'somewhat'
session.add(marten)
- shrew = Animal(u'shrew')
- shrew[u'cuteness'] = u'somewhat'
- shrew[u'poisonous-part'] = u'saliva'
+ shrew = Animal('shrew')
+ shrew['cuteness'] = 'somewhat'
+ shrew['poisonous-part'] = 'saliva'
session.add(shrew)
- loris = Animal(u'slow loris')
- loris[u'cuteness'] = u'fairly'
- loris[u'poisonous-part'] = u'elbows'
+ loris = Animal('slow loris')
+ loris['cuteness'] = 'fairly'
+ loris['poisonous-part'] = 'elbows'
session.add(loris)
session.commit()
q = (session.query(Animal).
filter(Animal.facts.any(
- and_(AnimalFact.key == u'color',
- AnimalFact.value == u'reddish'))))
- print 'reddish animals', q.all()
+ and_(AnimalFact.key == 'color',
+ AnimalFact.value == 'reddish'))))
+ print('reddish animals', q.all())
# Save some typing by wrapping that up in a function:
with_characteristic = lambda key, value: and_(AnimalFact.key == key,
@@ -226,21 +226,21 @@ if __name__ == '__main__':
q = (session.query(Animal).
filter(Animal.facts.any(
- with_characteristic(u'color', u'brown'))))
- print 'brown animals', q.all()
+ with_characteristic('color', 'brown'))))
+ print('brown animals', q.all())
q = (session.query(Animal).
filter(not_(Animal.facts.any(
- with_characteristic(u'poisonous-part', u'elbows')))))
- print 'animals without poisonous-part == elbows', q.all()
+ with_characteristic('poisonous-part', 'elbows')))))
+ print('animals without poisonous-part == elbows', q.all())
q = (session.query(Animal).
- filter(Animal.facts.any(AnimalFact.value == u'somewhat')))
- print 'any animal with any .value of "somewhat"', q.all()
+ filter(Animal.facts.any(AnimalFact.value == 'somewhat')))
+ print('any animal with any .value of "somewhat"', q.all())
# Facts can be queried as well.
q = (session.query(AnimalFact).
- filter(with_characteristic(u'cuteness', u'very')))
- print 'just the facts', q.all()
+ filter(with_characteristic('cuteness', 'very')))
+ print('just the facts', q.all())