Hybrid Attributes

Define attributes on ORM-mapped classes that have “hybrid” behavior.

“hybrid” means the attribute has distinct behaviors defined at theclass level and at the instance level.

The hybrid extension provides a special form ofmethod decorator, is around 50 lines of code and has almost nodependencies on the rest of SQLAlchemy. It can, in theory, work withany descriptor-based expression system.

Consider a mapping Interval, representing integer start and endvalues. We can define higher level functions on mapped classes that produce SQLexpressions at the class level, and Python expression evaluation at theinstance level. Below, each function decorated with hybrid_method orhybrid_property may receive self as an instance of the class, oras the class itself:

  1. from sqlalchemy import Column, Integer
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy.orm import Session, aliased
  4. from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
  5.  
  6. Base = declarative_base()
  7.  
  8. class Interval(Base):
  9. __tablename__ = 'interval'
  10.  
  11. id = Column(Integer, primary_key=True)
  12. start = Column(Integer, nullable=False)
  13. end = Column(Integer, nullable=False)
  14.  
  15. def __init__(self, start, end):
  16. self.start = start
  17. self.end = end
  18.  
  19. @hybrid_property
  20. def length(self):
  21. return self.end - self.start
  22.  
  23. @hybrid_method
  24. def contains(self, point):
  25. return (self.start <= point) & (point <= self.end)
  26.  
  27. @hybrid_method
  28. def intersects(self, other):
  29. return self.contains(other.start) | self.contains(other.end)

Above, the length property returns the difference between theend and start attributes. With an instance of Interval,this subtraction occurs in Python, using normal Python descriptormechanics:

  1. >>> i1 = Interval(5, 10)
  2. >>> i1.length
  3. 5

When dealing with the Interval class itself, the hybrid_propertydescriptor evaluates the function body given the Interval class asthe argument, which when evaluated with SQLAlchemy expression mechanicsreturns a new SQL expression:

  1. >>> print Interval.length
  2. interval."end" - interval.start
  3.  
  4. >>> print Session().query(Interval).filter(Interval.length > 10)
  5. SELECT interval.id AS interval_id, interval.start AS interval_start,
  6. interval."end" AS interval_end
  7. FROM interval
  8. WHERE interval."end" - interval.start > :param_1

ORM methods such as filter_by() generally use getattr() tolocate attributes, so can also be used with hybrid attributes:

  1. >>> print Session().query(Interval).filter_by(length=5)
  2. SELECT interval.id AS interval_id, interval.start AS interval_start,
  3. interval."end" AS interval_end
  4. FROM interval
  5. WHERE interval."end" - interval.start = :param_1

The Interval class example also illustrates two methods,contains() and intersects(), decorated withhybrid_method. This decorator applies the same idea tomethods that hybrid_property applies to attributes. Themethods return boolean values, and take advantage of the Python |and & bitwise operators to produce equivalent instance-level andSQL expression-level boolean behavior:

  1. >>> i1.contains(6)
  2. True
  3. >>> i1.contains(15)
  4. False
  5. >>> i1.intersects(Interval(7, 18))
  6. True
  7. >>> i1.intersects(Interval(25, 29))
  8. False
  9.  
  10. >>> print Session().query(Interval).filter(Interval.contains(15))
  11. SELECT interval.id AS interval_id, interval.start AS interval_start,
  12. interval."end" AS interval_end
  13. FROM interval
  14. WHERE interval.start <= :start_1 AND interval."end" > :end_1
  15.  
  16. >>> ia = aliased(Interval)
  17. >>> print Session().query(Interval, ia).filter(Interval.intersects(ia))
  18. SELECT interval.id AS interval_id, interval.start AS interval_start,
  19. interval."end" AS interval_end, interval_1.id AS interval_1_id,
  20. interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end
  21. FROM interval, interval AS interval_1
  22. WHERE interval.start <= interval_1.start
  23. AND interval."end" > interval_1.start
  24. OR interval.start <= interval_1."end"
  25. AND interval."end" > interval_1."end"

Defining Expression Behavior Distinct from Attribute Behavior

Our usage of the & and | bitwise operators above wasfortunate, considering our functions operated on two boolean values toreturn a new one. In many cases, the construction of an in-Pythonfunction and a SQLAlchemy SQL expression have enough differences thattwo separate Python expressions should be defined. Thehybrid decorators define thehybrid_property.expression() modifier for this purpose. As anexample we’ll define the radius of the interval, which requires theusage of the absolute value function:

  1. from sqlalchemy import func
  2.  
  3. class Interval(object):
  4. # ...
  5.  
  6. @hybrid_property
  7. def radius(self):
  8. return abs(self.length) / 2
  9.  
  10. @radius.expression
  11. def radius(cls):
  12. return func.abs(cls.length) / 2

Above the Python function abs() is used for instance-leveloperations, the SQL function ABS() is used via the funcobject for class-level expressions:

  1. >>> i1.radius
  2. 2
  3.  
  4. >>> print Session().query(Interval).filter(Interval.radius > 5)
  5. SELECT interval.id AS interval_id, interval.start AS interval_start,
  6. interval."end" AS interval_end
  7. FROM interval
  8. WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1

Note

When defining an expression for a hybrid property or method, theexpression method must retain the name of the original hybrid, elsethe new hybrid with the additional state will be attached to the classwith the non-matching name. To use the example above:

  1. class Interval(object):
  2. # ...
  3.  
  4. @hybrid_property
  5. def radius(self):
  6. return abs(self.length) / 2
  7.  
  8. # WRONG - the non-matching name will cause this function to be
  9. # ignored
  10. @radius.expression
  11. def radius_expression(cls):
  12. return func.abs(cls.length) / 2

This is also true for other mutator methods, such ashybrid_property.update_expression(). This is the same behavioras that of the @property construct that is part of standard Python.

Defining Setters

Hybrid properties can also define setter methods. If we wantedlength above, when set, to modify the endpoint value:

  1. class Interval(object):
  2. # ...
  3.  
  4. @hybrid_property
  5. def length(self):
  6. return self.end - self.start
  7.  
  8. @length.setter
  9. def length(self, value):
  10. self.end = self.start + value

The length(self, value) method is now called upon set:

  1. >>> i1 = Interval(5, 10)
  2. >>> i1.length
  3. 5
  4. >>> i1.length = 12
  5. >>> i1.end
  6. 17

Allowing Bulk ORM Update

A hybrid can define a custom “UPDATE” handler for when using theQuery.update() method, allowing the hybrid to be used in theSET clause of the update.

Normally, when using a hybrid with Query.update(), the SQLexpression is used as the column that’s the target of the SET. If ourInterval class had a hybrid start_point that linked toInterval.start, this could be substituted directly:

  1. session.query(Interval).update({Interval.start_point: 10})

However, when using a composite hybrid like Interval.length, thishybrid represents more than one column. We can set up a handler that willaccommodate a value passed to Query.update() which can affectthis, using the hybrid_property.update_expression() decorator.A handler that works similarly to our setter would be:

  1. class Interval(object):
  2. # ...
  3.  
  4. @hybrid_property
  5. def length(self):
  6. return self.end - self.start
  7.  
  8. @length.setter
  9. def length(self, value):
  10. self.end = self.start + value
  11.  
  12. @length.update_expression
  13. def length(cls, value):
  14. return [
  15. (cls.end, cls.start + value)
  16. ]

Above, if we use Interval.length in an UPDATE expression as:

  1. session.query(Interval).update(
  2. {Interval.length: 25}, synchronize_session='fetch')

We’ll get an UPDATE statement along the lines of:

  1. UPDATE interval SET end=start + :value

In some cases, the default “evaluate” strategy can’t perform the SETexpression in Python; while the addition operator we’re using aboveis supported, for more complex SET expressions it will usually be necessaryto use either the “fetch” or False synchronization strategy as illustratedabove.

New in version 1.2: added support for bulk updates to hybrid properties.

Working with Relationships

There’s no essential difference when creating hybrids that work withrelated objects as opposed to column-based data. The need for distinctexpressions tends to be greater. The two variants we’ll illustrateare the “join-dependent” hybrid, and the “correlated subquery” hybrid.

Join-Dependent Relationship Hybrid

Consider the following declarativemapping which relates a User to a SavingsAccount:

  1. from sqlalchemy import Column, Integer, ForeignKey, Numeric, String
  2. from sqlalchemy.orm import relationship
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.ext.hybrid import hybrid_property
  5.  
  6. Base = declarative_base()
  7.  
  8. class SavingsAccount(Base):
  9. __tablename__ = 'account'
  10. id = Column(Integer, primary_key=True)
  11. user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
  12. balance = Column(Numeric(15, 5))
  13.  
  14. class User(Base):
  15. __tablename__ = 'user'
  16. id = Column(Integer, primary_key=True)
  17. name = Column(String(100), nullable=False)
  18.  
  19. accounts = relationship("SavingsAccount", backref="owner")
  20.  
  21. @hybrid_property
  22. def balance(self):
  23. if self.accounts:
  24. return self.accounts[0].balance
  25. else:
  26. return None
  27.  
  28. @balance.setter
  29. def balance(self, value):
  30. if not self.accounts:
  31. account = Account(owner=self)
  32. else:
  33. account = self.accounts[0]
  34. account.balance = value
  35.  
  36. @balance.expression
  37. def balance(cls):
  38. return SavingsAccount.balance

The above hybrid property balance works with the firstSavingsAccount entry in the list of accounts for this user. Thein-Python getter/setter methods can treat accounts as a Pythonlist available on self.

However, at the expression level, it’s expected that the User class willbe used in an appropriate context such that an appropriate join toSavingsAccount will be present:

  1. >>> print Session().query(User, User.balance).\
  2. ... join(User.accounts).filter(User.balance > 5000)
  3. SELECT "user".id AS user_id, "user".name AS user_name,
  4. account.balance AS account_balance
  5. FROM "user" JOIN account ON "user".id = account.user_id
  6. WHERE account.balance > :balance_1

Note however, that while the instance level accessors need to worryabout whether self.accounts is even present, this issue expressesitself differently at the SQL expression level, where we basicallywould use an outer join:

  1. >>> from sqlalchemy import or_
  2. >>> print (Session().query(User, User.balance).outerjoin(User.accounts).
  3. ... filter(or_(User.balance < 5000, User.balance == None)))
  4. SELECT "user".id AS user_id, "user".name AS user_name,
  5. account.balance AS account_balance
  6. FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id
  7. WHERE account.balance < :balance_1 OR account.balance IS NULL

Correlated Subquery Relationship Hybrid

We can, of course, forego being dependent on the enclosing query’s usageof joins in favor of the correlated subquery, which can portably be packedinto a single column expression. A correlated subquery is more portable, butoften performs more poorly at the SQL level. Using the same techniqueillustrated at Using column_property,we can adjust our SavingsAccount example to aggregate the balances forall accounts, and use a correlated subquery for the column expression:

  1. from sqlalchemy import Column, Integer, ForeignKey, Numeric, String
  2. from sqlalchemy.orm import relationship
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.ext.hybrid import hybrid_property
  5. from sqlalchemy import select, func
  6.  
  7. Base = declarative_base()
  8.  
  9. class SavingsAccount(Base):
  10. __tablename__ = 'account'
  11. id = Column(Integer, primary_key=True)
  12. user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
  13. balance = Column(Numeric(15, 5))
  14.  
  15. class User(Base):
  16. __tablename__ = 'user'
  17. id = Column(Integer, primary_key=True)
  18. name = Column(String(100), nullable=False)
  19.  
  20. accounts = relationship("SavingsAccount", backref="owner")
  21.  
  22. @hybrid_property
  23. def balance(self):
  24. return sum(acc.balance for acc in self.accounts)
  25.  
  26. @balance.expression
  27. def balance(cls):
  28. return select([func.sum(SavingsAccount.balance)]).\
  29. where(SavingsAccount.user_id==cls.id).\
  30. label('total_balance')

The above recipe will give us the balance column which rendersa correlated SELECT:

  1. >>> print s.query(User).filter(User.balance > 400)
  2. SELECT "user".id AS user_id, "user".name AS user_name
  3. FROM "user"
  4. WHERE (SELECT sum(account.balance) AS sum_1
  5. FROM account
  6. WHERE account.user_id = "user".id) > :param_1

Building Custom Comparators

The hybrid property also includes a helper that allows construction ofcustom comparators. A comparator object allows one to customize thebehavior of each SQLAlchemy expression operator individually. Theyare useful when creating custom types that have some highlyidiosyncratic behavior on the SQL side.

Note

The hybrid_property.comparator() decorator introducedin this section replaces the use of thehybrid_property.expression() decorator.They cannot be used together.

The example class below allows case-insensitive comparisons on the attributenamed word_insensitive:

  1. from sqlalchemy.ext.hybrid import Comparator, hybrid_property
  2. from sqlalchemy import func, Column, Integer, String
  3. from sqlalchemy.orm import Session
  4. from sqlalchemy.ext.declarative import declarative_base
  5.  
  6. Base = declarative_base()
  7.  
  8. class CaseInsensitiveComparator(Comparator):
  9. def __eq__(self, other):
  10. return func.lower(self.__clause_element__()) == func.lower(other)
  11.  
  12. class SearchWord(Base):
  13. __tablename__ = 'searchword'
  14. id = Column(Integer, primary_key=True)
  15. word = Column(String(255), nullable=False)
  16.  
  17. @hybrid_property
  18. def word_insensitive(self):
  19. return self.word.lower()
  20.  
  21. @word_insensitive.comparator
  22. def word_insensitive(cls):
  23. return CaseInsensitiveComparator(cls.word)

Above, SQL expressions against word_insensitive will apply the LOWER()SQL function to both sides:

  1. >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks")
  2. SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
  3. FROM searchword
  4. WHERE lower(searchword.word) = lower(:lower_1)

The CaseInsensitiveComparator above implements part of theColumnOperators interface. A “coercion” operation likelowercasing can be applied to all comparison operations (i.e. eq,lt, gt, etc.) using Operators.operate():

  1. class CaseInsensitiveComparator(Comparator):
  2. def operate(self, op, other):
  3. return op(func.lower(self.__clause_element__()), func.lower(other))

Reusing Hybrid Properties across Subclasses

A hybrid can be referred to from a superclass, to allow modifyingmethods like hybrid_property.getter(), hybrid_property.setter()to be used to redefine those methods on a subclass. This is similar tohow the standard Python @property object works:

  1. class FirstNameOnly(Base):
  2. # ...
  3.  
  4. first_name = Column(String)
  5.  
  6. @hybrid_property
  7. def name(self):
  8. return self.first_name
  9.  
  10. @name.setter
  11. def name(self, value):
  12. self.first_name = value
  13.  
  14. class FirstNameLastName(FirstNameOnly):
  15. # ...
  16.  
  17. last_name = Column(String)
  18.  
  19. @FirstNameOnly.name.getter
  20. def name(self):
  21. return self.first_name + ' ' + self.last_name
  22.  
  23. @name.setter
  24. def name(self, value):
  25. self.first_name, self.last_name = value.split(' ', 1)

Above, the FirstNameLastName class refers to the hybrid fromFirstNameOnly.name to repurpose its getter and setter for the subclass.

When overriding hybrid_property.expression() andhybrid_property.comparator() alone as the first reference to thesuperclass, these names conflict with the same-named accessors on the class-level QueryableAttribute object returned at the class level. Tooverride these methods when referring directly to the parent class descriptor,add the special qualifier hybrid_property.overrides, which will de-reference the instrumented attribute back to the hybrid object:

  1. class FirstNameLastName(FirstNameOnly):
  2. # ...
  3.  
  4. last_name = Column(String)
  5.  
  6. @FirstNameOnly.name.overrides.expression
  7. def name(cls):
  8. return func.concat(cls.first_name, ' ', cls.last_name)

New in version 1.2: Added hybrid_property.getter() as well as theability to redefine accessors per-subclass.

Hybrid Value Objects

Note in our previous example, if we were to compare the word_insensitiveattribute of a SearchWord instance to a plain Python string, the plainPython string would not be coerced to lower case - theCaseInsensitiveComparator we built, being returned by@word_insensitive.comparator, only applies to the SQL side.

A more comprehensive form of the custom comparator is to construct a HybridValue Object. This technique applies the target value or expression to a valueobject which is then returned by the accessor in all cases. The value objectallows control of all operations upon the value as well as how compared valuesare treated, both on the SQL expression side as well as the Python value side.Replacing the previous CaseInsensitiveComparator class with a newCaseInsensitiveWord class:

  1. class CaseInsensitiveWord(Comparator):
  2. "Hybrid value representing a lower case representation of a word."
  3.  
  4. def __init__(self, word):
  5. if isinstance(word, basestring):
  6. self.word = word.lower()
  7. elif isinstance(word, CaseInsensitiveWord):
  8. self.word = word.word
  9. else:
  10. self.word = func.lower(word)
  11.  
  12. def operate(self, op, other):
  13. if not isinstance(other, CaseInsensitiveWord):
  14. other = CaseInsensitiveWord(other)
  15. return op(self.word, other.word)
  16.  
  17. def __clause_element__(self):
  18. return self.word
  19.  
  20. def __str__(self):
  21. return self.word
  22.  
  23. key = 'word'
  24. "Label to apply to Query tuple results"

Above, the CaseInsensitiveWord object represents self.word, which maybe a SQL function, or may be a Python native. By overriding operate() andclause_element() to work in terms of self.word, all comparisonoperations will work against the “converted” form of word, whether it beSQL side or Python side. Our SearchWord class can now deliver theCaseInsensitiveWord object unconditionally from a single hybrid call:

  1. class SearchWord(Base):
  2. __tablename__ = 'searchword'
  3. id = Column(Integer, primary_key=True)
  4. word = Column(String(255), nullable=False)
  5.  
  6. @hybrid_property
  7. def word_insensitive(self):
  8. return CaseInsensitiveWord(self.word)

The word_insensitive attribute now has case-insensitive comparison behavioruniversally, including SQL expression vs. Python expression (note the Pythonvalue is converted to lower case on the Python side here):

  1. >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks")
  2. SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
  3. FROM searchword
  4. WHERE lower(searchword.word) = :lower_1

SQL expression versus SQL expression:

  1. >>> sw1 = aliased(SearchWord)
  2. >>> sw2 = aliased(SearchWord)
  3. >>> print Session().query(
  4. ... sw1.word_insensitive,
  5. ... sw2.word_insensitive).\
  6. ... filter(
  7. ... sw1.word_insensitive > sw2.word_insensitive
  8. ... )
  9. SELECT lower(searchword_1.word) AS lower_1,
  10. lower(searchword_2.word) AS lower_2
  11. FROM searchword AS searchword_1, searchword AS searchword_2
  12. WHERE lower(searchword_1.word) > lower(searchword_2.word)

Python only expression:

  1. >>> ws1 = SearchWord(word="SomeWord")
  2. >>> ws1.word_insensitive == "sOmEwOrD"
  3. True
  4. >>> ws1.word_insensitive == "XOmEwOrX"
  5. False
  6. >>> print ws1.word_insensitive
  7. someword

The Hybrid Value pattern is very useful for any kind of value that may havemultiple representations, such as timestamps, time deltas, units ofmeasurement, currencies and encrypted passwords.

See also

Hybrids and Value Agnostic Types- on the techspot.zzzeek.org blog

Value Agnostic Types, Part II -on the techspot.zzzeek.org blog

Building Transformers

A transformer is an object which can receive a Query object andreturn a new one. The Query object includes a methodwith_transformation() that returns a new Query transformed bythe given function.

We can combine this with the Comparator class to produce one typeof recipe which can both set up the FROM clause of a query as well as assignfiltering criterion.

Consider a mapped class Node, which assembles using adjacency list into ahierarchical tree pattern:

  1. from sqlalchemy import Column, Integer, ForeignKey
  2. from sqlalchemy.orm import relationship
  3. from sqlalchemy.ext.declarative import declarative_base
  4. Base = declarative_base()
  5.  
  6. class Node(Base):
  7. __tablename__ = 'node'
  8. id = Column(Integer, primary_key=True)
  9. parent_id = Column(Integer, ForeignKey('node.id'))
  10. parent = relationship("Node", remote_side=id)

Suppose we wanted to add an accessor grandparent. This would return theparent of Node.parent. When we have an instance of Node, this issimple:

  1. from sqlalchemy.ext.hybrid import hybrid_property
  2.  
  3. class Node(Base):
  4. # ...
  5.  
  6. @hybrid_property
  7. def grandparent(self):
  8. return self.parent.parent

For the expression, things are not so clear. We’d need to construct aQuery where we join() twice along Node.parent toget to the grandparent. We can instead return a transforming callablethat we’ll combine with the Comparator class to receive anyQuery object, and return a new one that’s joined to theNode.parent attribute and filtered based on the given criterion:

  1. from sqlalchemy.ext.hybrid import Comparator
  2.  
  3. class GrandparentTransformer(Comparator):
  4. def operate(self, op, other):
  5. def transform(q):
  6. cls = self.__clause_element__()
  7. parent_alias = aliased(cls)
  8. return q.join(parent_alias, cls.parent).\
  9. filter(op(parent_alias.parent, other))
  10. return transform
  11.  
  12. Base = declarative_base()
  13.  
  14. class Node(Base):
  15. __tablename__ = 'node'
  16. id =Column(Integer, primary_key=True)
  17. parent_id = Column(Integer, ForeignKey('node.id'))
  18. parent = relationship("Node", remote_side=id)
  19.  
  20. @hybrid_property
  21. def grandparent(self):
  22. return self.parent.parent
  23.  
  24. @grandparent.comparator
  25. def grandparent(cls):
  26. return GrandparentTransformer(cls)

The GrandparentTransformer overrides the core Operators.operate()method at the base of the Comparator hierarchy to return a query-transforming callable, which then runs the given comparison operation in aparticular context. Such as, in the example above, the operate method iscalled, given the Operators.eq callable as well as the right side ofthe comparison Node(id=5). A function transform is then returned whichwill transform a Query first to join to Node.parent, then tocompare parent_alias using Operators.eq against the left and rightsides, passing into Query.filter:

  1. >>> from sqlalchemy.orm import Session
  2. >>> session = Session()
  3. sql>>> session.query(Node).\
  4. ... with_transformation(Node.grandparent==Node(id=5)).\
  5. ... all()
  6. SELECT node.id AS node_id, node.parent_id AS node_parent_id
  7. FROM node JOIN node AS node_1 ON node_1.id = node.parent_id
  8. WHERE :param_1 = node_1.parent_id

We can modify the pattern to be more verbose but flexible by separating the“join” step from the “filter” step. The tricky part here is ensuring thatsuccessive instances of GrandparentTransformer use the sameAliasedClass object against Node. Below we use a simplememoizing approach that associates a GrandparentTransformer with eachclass:

  1. class Node(Base):
  2.  
  3. # ...
  4.  
  5. @grandparent.comparator
  6. def grandparent(cls):
  7. # memoize a GrandparentTransformer
  8. # per class
  9. if '_gp' not in cls.__dict__:
  10. cls._gp = GrandparentTransformer(cls)
  11. return cls._gp
  12.  
  13. class GrandparentTransformer(Comparator):
  14.  
  15. def __init__(self, cls):
  16. self.parent_alias = aliased(cls)
  17.  
  18. @property
  19. def join(self):
  20. def go(q):
  21. return q.join(self.parent_alias, Node.parent)
  22. return go
  23.  
  24. def operate(self, op, other):
  25. return op(self.parent_alias.parent, other)
  1. sql>>> session.query(Node).\
  2. ... with_transformation(Node.grandparent.join).\
  3. ... filter(Node.grandparent==Node(id=5))
  4. SELECT node.id AS node_id, node.parent_id AS node_parent_id
  5. FROM node JOIN node AS node_1 ON node_1.id = node.parent_id
  6. WHERE :param_1 = node_1.parent_id

The “transformer” pattern is an experimental pattern that starts to make usageof some functional programming paradigms. While it’s only recommended foradvanced and/or patient developers, there’s probably a whole lot of amazingthings it can be used for.

API Reference

A decorator which allows definition of a Python object method with bothinstance-level and class-level behavior.

Usage is typically via decorator:

  1. from sqlalchemy.ext.hybrid import hybrid_method
  2.  
  3. class SomeClass(object):
  4. @hybrid_method
  5. def value(self, x, y):
  6. return self._value + x + y
  7.  
  8. @value.expression
  9. def value(self, x, y):
  10. return func.some_function(self._value, x, y)
  • expression(expr)
  • Provide a modifying decorator that defines aSQL-expression producing method.

A decorator which allows definition of a Python descriptor with bothinstance-level and class-level behavior.

  • init(fget, fset=None, fdel=None, expr=None, custom_comparator=None, update_expr=None)
  • Create a new hybrid_property.

Usage is typically via decorator:

  1. from sqlalchemy.ext.hybrid import hybrid_property
  2.  
  3. class SomeClass(object):
  4. @hybrid_property
  5. def value(self):
  6. return self._value
  7.  
  8. @value.setter
  9. def value(self, value):
  10. self._value = value
  • comparator(comparator)
  • Provide a modifying decorator that defines a customcomparator producing method.

The return value of the decorated method should be an instance ofComparator.

Note

The hybrid_property.comparator() decoratorreplaces the use of the hybrid_property.expression()decorator. They cannot be used together.

When a hybrid is invoked at the class level, theComparator object given here is wrapped inside of aspecialized QueryableAttribute, which is the same kind ofobject used by the ORM to represent other mapped attributes. Thereason for this is so that other class-level attributes such asdocstrings and a reference to the hybrid itself may be maintainedwithin the structure that’s returned, without any modifications to theoriginal comparator object passed in.

Note

when referring to a hybrid property from an owning class (e.g.SomeClass.some_hybrid), an instance ofQueryableAttribute is returned, representing theexpression or comparator object as this hybrid object. However,that object itself has accessors called expression andcomparator; so when attempting to override these decorators on asubclass, it may be necessary to qualify it using thehybrid_property.overrides modifier first. See thatmodifier for details.

  • deleter(fdel)
  • Provide a modifying decorator that defines a deletion method.

  • expression(expr)

  • Provide a modifying decorator that defines a SQL-expressionproducing method.

When a hybrid is invoked at the class level, the SQL expression givenhere is wrapped inside of a specialized QueryableAttribute,which is the same kind of object used by the ORM to represent othermapped attributes. The reason for this is so that other class-levelattributes such as docstrings and a reference to the hybrid itself maybe maintained within the structure that’s returned, without anymodifications to the original SQL expression passed in.

Note

when referring to a hybrid property from an owning class (e.g.SomeClass.some_hybrid), an instance ofQueryableAttribute is returned, representing theexpression or comparator object as well as this hybrid object.However, that object itself has accessors called expression andcomparator; so when attempting to override these decorators on asubclass, it may be necessary to qualify it using thehybrid_property.overrides modifier first. See thatmodifier for details.

See also

Defining Expression Behavior Distinct from Attribute Behavior

  • getter(fget)
  • Provide a modifying decorator that defines a getter method.

New in version 1.2.

  • property overrides
  • Prefix for a method that is overriding an existing attribute.

The hybrid_property.overrides accessor just returnsthis hybrid object, which when called at the class level froma parent class, will de-reference the “instrumented attribute”normally returned at this level, and allow modifying decoratorslike hybrid_property.expression() andhybrid_property.comparator()to be used without conflicting with the same-named attributesnormally present on the QueryableAttribute:

  1. class SuperClass(object):
  2. # ...
  3.  
  4. @hybrid_property
  5. def foobar(self):
  6. return self._foobar
  7.  
  8. class SubClass(SuperClass):
  9. # ...
  10.  
  11. @SuperClass.foobar.overrides.expression
  12. def foobar(cls):
  13. return func.subfoobar(self._foobar)

New in version 1.2.

See also

Reusing Hybrid Properties across Subclasses

  • setter(fset)
  • Provide a modifying decorator that defines a setter method.

  • updateexpression(_meth)

  • Provide a modifying decorator that defines an UPDATE tupleproducing method.

The method accepts a single value, which is the value to berendered into the SET clause of an UPDATE statement. The methodshould then process this value into individual column expressionsthat fit into the ultimate SET clause, and return them as asequence of 2-tuples. Each tuplecontains a column expression as the key and a value to be rendered.

E.g.:

  1. class Person(Base):
  2. # ...
  3.  
  4. first_name = Column(String)
  5. last_name = Column(String)
  6.  
  7. @hybrid_property
  8. def fullname(self):
  9. return first_name + " " + last_name
  10.  
  11. @fullname.update_expression
  12. def fullname(cls, value):
  13. fname, lname = value.split(" ", 1)
  14. return [
  15. (cls.first_name, fname),
  16. (cls.last_name, lname)
  17. ]

New in version 1.2.

A helper class that allows easy construction of customPropComparatorclasses for usage with hybrids.

  • sqlalchemy.ext.hybrid.HYBRIDMETHOD = symbol('HYBRIDMETHOD')
  • Symbol indicating an InspectionAttr that’sof type hybrid_method.

Is assigned to the InspectionAttr.extension_typeattribute.

See also

Mapper.all_orm_attributes

  • sqlalchemy.ext.hybrid.HYBRIDPROPERTY = symbol('HYBRIDPROPERTY')
    • Symbol indicating an InspectionAttr that’s
    • of type hybrid_method.

Is assigned to the InspectionAttr.extension_typeattribute.

See also

Mapper.all_orm_attributes