Hybrid Attributes

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

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

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

Consider a mapping Interval, representing integer start and end values. We can define higher level functions on mapped classes that produce SQL expressions at the class level, and Python expression evaluation at the instance level. Below, each function decorated with hybrid_method or hybrid_property may receive self as an instance of the class, or as 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. Base = declarative_base()
  6. class Interval(Base):
  7. __tablename__ = 'interval'
  8. id = Column(Integer, primary_key=True)
  9. start = Column(Integer, nullable=False)
  10. end = Column(Integer, nullable=False)
  11. def __init__(self, start, end):
  12. self.start = start
  13. self.end = end
  14. @hybrid_property
  15. def length(self):
  16. return self.end - self.start
  17. @hybrid_method
  18. def contains(self, point):
  19. return (self.start <= point) & (point <= self.end)
  20. @hybrid_method
  21. def intersects(self, other):
  22. return self.contains(other.start) | self.contains(other.end)

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

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

When dealing with the Interval class itself, the hybrid_property descriptor evaluates the function body given the Interval class as the argument, which when evaluated with SQLAlchemy expression mechanics (here using the QueryableAttribute.expression accessor) returns a new SQL expression:

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

ORM methods such as Query.filter_by() generally use getattr() to locate 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 with hybrid_method. This decorator applies the same idea to methods that hybrid_property applies to attributes. The methods return boolean values, and take advantage of the Python | and & bitwise operators to produce equivalent instance-level and SQL 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. >>> print(Session().query(Interval).filter(Interval.contains(15)))
  10. SELECT interval.id AS interval_id, interval.start AS interval_start,
  11. interval."end" AS interval_end
  12. FROM interval
  13. WHERE interval.start <= :start_1 AND interval."end" > :end_1
  14. >>> ia = aliased(Interval)
  15. >>> print(Session().query(Interval, ia).filter(Interval.intersects(ia)))
  16. SELECT interval.id AS interval_id, interval.start AS interval_start,
  17. interval."end" AS interval_end, interval_1.id AS interval_1_id,
  18. interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end
  19. FROM interval, interval AS interval_1
  20. WHERE interval.start <= interval_1.start
  21. AND interval."end" > interval_1.start
  22. OR interval.start <= interval_1."end"
  23. AND interval."end" > interval_1."end"

Defining Expression Behavior Distinct from Attribute Behavior

Our usage of the & and | bitwise operators above was fortunate, considering our functions operated on two boolean values to return a new one. In many cases, the construction of an in-Python function and a SQLAlchemy SQL expression have enough differences that two separate Python expressions should be defined. The hybrid decorators define the hybrid_property.expression() modifier for this purpose. As an example we’ll define the radius of the interval, which requires the usage of the absolute value function:

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

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

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

Note

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

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

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

Defining Setters

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

  1. class Interval(object):
  2. # ...
  3. @hybrid_property
  4. def length(self):
  5. return self.end - self.start
  6. @length.setter
  7. def length(self, value):
  8. 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 the Query.update() method, allowing the hybrid to be used in the SET clause of the update.

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

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

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

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

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 SET expression in Python; while the addition operator we’re using above is supported, for more complex SET expressions it will usually be necessary to use either the “fetch” or False synchronization strategy as illustrated above.

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 with related objects as opposed to column-based data. The need for distinct expressions tends to be greater. The two variants we’ll illustrate are the “join-dependent” hybrid, and the “correlated subquery” hybrid.

Join-Dependent Relationship Hybrid

Consider the following declarative mapping 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. Base = declarative_base()
  6. class SavingsAccount(Base):
  7. __tablename__ = 'account'
  8. id = Column(Integer, primary_key=True)
  9. user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
  10. balance = Column(Numeric(15, 5))
  11. class User(Base):
  12. __tablename__ = 'user'
  13. id = Column(Integer, primary_key=True)
  14. name = Column(String(100), nullable=False)
  15. accounts = relationship("SavingsAccount", backref="owner")
  16. @hybrid_property
  17. def balance(self):
  18. if self.accounts:
  19. return self.accounts[0].balance
  20. else:
  21. return None
  22. @balance.setter
  23. def balance(self, value):
  24. if not self.accounts:
  25. account = Account(owner=self)
  26. else:
  27. account = self.accounts[0]
  28. account.balance = value
  29. @balance.expression
  30. def balance(cls):
  31. return SavingsAccount.balance

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

However, at the expression level, it’s expected that the User class will be used in an appropriate context such that an appropriate join to SavingsAccount 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 worry about whether self.accounts is even present, this issue expresses itself differently at the SQL expression level, where we basically would 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 usage of joins in favor of the correlated subquery, which can portably be packed into a single column expression. A correlated subquery is more portable, but often performs more poorly at the SQL level. Using the same technique illustrated at Using column_property, we can adjust our SavingsAccount example to aggregate the balances for all 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. Base = declarative_base()
  7. class SavingsAccount(Base):
  8. __tablename__ = 'account'
  9. id = Column(Integer, primary_key=True)
  10. user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
  11. balance = Column(Numeric(15, 5))
  12. class User(Base):
  13. __tablename__ = 'user'
  14. id = Column(Integer, primary_key=True)
  15. name = Column(String(100), nullable=False)
  16. accounts = relationship("SavingsAccount", backref="owner")
  17. @hybrid_property
  18. def balance(self):
  19. return sum(acc.balance for acc in self.accounts)
  20. @balance.expression
  21. def balance(cls):
  22. return select(func.sum(SavingsAccount.balance)).\
  23. where(SavingsAccount.user_id==cls.id).\
  24. label('total_balance')

The above recipe will give us the balance column which renders a 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 of custom comparators. A comparator object allows one to customize the behavior of each SQLAlchemy expression operator individually. They are useful when creating custom types that have some highly idiosyncratic behavior on the SQL side.

Note

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

The example class below allows case-insensitive comparisons on the attribute named 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. Base = declarative_base()
  6. class CaseInsensitiveComparator(Comparator):
  7. def __eq__(self, other):
  8. return func.lower(self.__clause_element__()) == func.lower(other)
  9. class SearchWord(Base):
  10. __tablename__ = 'searchword'
  11. id = Column(Integer, primary_key=True)
  12. word = Column(String(255), nullable=False)
  13. @hybrid_property
  14. def word_insensitive(self):
  15. return self.word.lower()
  16. @word_insensitive.comparator
  17. def word_insensitive(cls):
  18. 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 the ColumnOperators interface. A “coercion” operation like lowercasing 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 modifying methods like hybrid_property.getter(), hybrid_property.setter() to be used to redefine those methods on a subclass. This is similar to how the standard Python @property object works:

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

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

When overriding hybrid_property.expression() and hybrid_property.comparator() alone as the first reference to the superclass, these names conflict with the same-named accessors on the class- level QueryableAttribute object returned at the class level. To override 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. last_name = Column(String)
  4. @FirstNameOnly.name.overrides.expression
  5. def name(cls):
  6. return func.concat(cls.first_name, ' ', cls.last_name)

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

Hybrid Value Objects

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

A more comprehensive form of the custom comparator is to construct a Hybrid Value Object. This technique applies the target value or expression to a value object which is then returned by the accessor in all cases. The value object allows control of all operations upon the value as well as how compared values are treated, both on the SQL expression side as well as the Python value side. Replacing the previous CaseInsensitiveComparator class with a new CaseInsensitiveWord class:

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

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

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

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

  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 have multiple representations, such as timestamps, time deltas, units of measurement, 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 and return a new one. The Query object includes a method with_transformation() that returns a new Query transformed by the given function.

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

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

  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. class Node(Base):
  6. __tablename__ = 'node'
  7. id = Column(Integer, primary_key=True)
  8. parent_id = Column(Integer, ForeignKey('node.id'))
  9. parent = relationship("Node", remote_side=id)

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

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

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

  1. from sqlalchemy.ext.hybrid import Comparator
  2. class GrandparentTransformer(Comparator):
  3. def operate(self, op, other):
  4. def transform(q):
  5. cls = self.__clause_element__()
  6. parent_alias = aliased(cls)
  7. return q.join(parent_alias, cls.parent).\
  8. filter(op(parent_alias.parent, other))
  9. return transform
  10. Base = declarative_base()
  11. class Node(Base):
  12. __tablename__ = 'node'
  13. id = Column(Integer, primary_key=True)
  14. parent_id = Column(Integer, ForeignKey('node.id'))
  15. parent = relationship("Node", remote_side=id)
  16. @hybrid_property
  17. def grandparent(self):
  18. return self.parent.parent
  19. @grandparent.comparator
  20. def grandparent(cls):
  21. 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 a particular context. Such as, in the example above, the operate method is called, given the Operators.eq callable as well as the right side of the comparison Node(id=5). A function transform is then returned which will transform a Query first to join to Node.parent, then to compare parent_alias using Operators.eq against the left and right sides, 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 that successive instances of GrandparentTransformer use the same AliasedClass object against Node. Below we use a simple memoizing approach that associates a GrandparentTransformer with each class:

  1. class Node(Base):
  2. # ...
  3. @grandparent.comparator
  4. def grandparent(cls):
  5. # memoize a GrandparentTransformer
  6. # per class
  7. if '_gp' not in cls.__dict__:
  8. cls._gp = GrandparentTransformer(cls)
  9. return cls._gp
  10. class GrandparentTransformer(Comparator):
  11. def __init__(self, cls):
  12. self.parent_alias = aliased(cls)
  13. @property
  14. def join(self):
  15. def go(q):
  16. return q.join(self.parent_alias, Node.parent)
  17. return go
  18. def operate(self, op, other):
  19. 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 usage of some functional programming paradigms. While it’s only recommended for advanced and/or patient developers, there’s probably a whole lot of amazing things it can be used for.

API Reference

Object NameDescription

Comparator

A helper class that allows easy construction of custom PropComparator classes for usage with hybrids.

hybrid_method

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

HYBRID_METHOD

Symbol indicating an InspectionAttr that’s of type hybrid_method.

hybrid_property

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

HYBRID_PROPERTY

class sqlalchemy.ext.hybrid.``hybrid_method(func, expr=None)

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

Class signature

class sqlalchemy.ext.hybrid.hybrid_method (sqlalchemy.orm.base.InspectionAttrInfo)

  • method sqlalchemy.ext.hybrid.hybrid_method.__init__(func, expr=None)

    Create a new hybrid_method.

    Usage is typically via decorator:

    1. from sqlalchemy.ext.hybrid import hybrid_method
    2. class SomeClass(object):
    3. @hybrid_method
    4. def value(self, x, y):
    5. return self._value + x + y
    6. @value.expression
    7. def value(self, x, y):
    8. return func.some_function(self._value, x, y)
  • method sqlalchemy.ext.hybrid.hybrid_method.expression(expr)

    Provide a modifying decorator that defines a SQL-expression producing method.

class sqlalchemy.ext.hybrid.``hybrid_property(fget, fset=None, fdel=None, expr=None, custom_comparator=None, update_expr=None)

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

Class signature

class sqlalchemy.ext.hybrid.hybrid_property (sqlalchemy.orm.base.InspectionAttrInfo)

  • method sqlalchemy.ext.hybrid.hybrid_property.__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. class SomeClass(object):
    3. @hybrid_property
    4. def value(self):
    5. return self._value
    6. @value.setter
    7. def value(self, value):
    8. self._value = value
  • method sqlalchemy.ext.hybrid.hybrid_property.comparator(comparator)

    Provide a modifying decorator that defines a custom comparator producing method.

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

    Note

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

    When a hybrid is invoked at the class level, the Comparator object given here is wrapped inside of a specialized QueryableAttribute, which is the same kind of object used by the ORM to represent other mapped attributes. The reason for this is so that other class-level attributes such as docstrings and a reference to the hybrid itself may be maintained within the structure that’s returned, without any modifications to the original comparator object passed in.

    Note

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

  • method sqlalchemy.ext.hybrid.hybrid_property.deleter(fdel)

    Provide a modifying decorator that defines a deletion method.

  • method sqlalchemy.ext.hybrid.hybrid_property.expression(expr)

    Provide a modifying decorator that defines a SQL-expression producing method.

    When a hybrid is invoked at the class level, the SQL expression given here is wrapped inside of a specialized QueryableAttribute, which is the same kind of object used by the ORM to represent other mapped attributes. The reason for this is so that other class-level attributes such as docstrings and a reference to the hybrid itself may be maintained within the structure that’s returned, without any modifications 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 of QueryableAttribute is returned, representing the expression or comparator object as well as this hybrid object. However, that object itself has accessors called expression and comparator; so when attempting to override these decorators on a subclass, it may be necessary to qualify it using the hybrid_property.overrides modifier first. See that modifier for details.

    See also

    Defining Expression Behavior Distinct from Attribute Behavior

  • method sqlalchemy.ext.hybrid.hybrid_property.getter(fget)

    Provide a modifying decorator that defines a getter method.

    New in version 1.2.

  • attribute sqlalchemy.ext.hybrid.hybrid_property.overrides

    Prefix for a method that is overriding an existing attribute.

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

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

    New in version 1.2.

    See also

    Reusing Hybrid Properties across Subclasses

  • method sqlalchemy.ext.hybrid.hybrid_property.setter(fset)

    Provide a modifying decorator that defines a setter method.

  • method sqlalchemy.ext.hybrid.hybrid_property.update_expression(meth)

    Provide a modifying decorator that defines an UPDATE tuple producing method.

    The method accepts a single value, which is the value to be rendered into the SET clause of an UPDATE statement. The method should then process this value into individual column expressions that fit into the ultimate SET clause, and return them as a sequence of 2-tuples. Each tuple contains a column expression as the key and a value to be rendered.

    E.g.:

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

    New in version 1.2.

class sqlalchemy.ext.hybrid.``Comparator(expression)

A helper class that allows easy construction of custom PropComparator classes for usage with hybrids.

Class signature

class sqlalchemy.ext.hybrid.Comparator (sqlalchemy.orm.PropComparator)

sqlalchemy.ext.hybrid.``HYBRID_METHOD = symbol(‘HYBRID_METHOD’)

Symbol indicating an InspectionAttr that’s of type hybrid_method.

Is assigned to the InspectionAttr.extension_type attribute.

See also

Mapper.all_orm_attributes

sqlalchemy.ext.hybrid.``HYBRID_PROPERTY = symbol(‘HYBRID_PROPERTY’)

  • Symbol indicating an InspectionAttr that’s

    of type hybrid_method.

Is assigned to the InspectionAttr.extension_type attribute.

See also

Mapper.all_orm_attributes