Function relator mixin


Base for database models with relationships to Function models. It provides automatic conversion of functions to Function models when setting attributes.


In the setup, we create a SQLAlchemy session, define a Parent model subclassing FunctionRelator, and a Function model subclassing FunctionMixin.

from sqlalchemy_function import FunctionMixin, FunctionRelator

# standard session creation
from sqlalchemy import create_engine, Column, ForeignKey, Integer
from sqlalchemy.orm import relationship, sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///:memory:')
session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)
session = Session()
Base = declarative_base()

# subclass `FunctionRelator` for models with a relationship to Function models
class Parent(FunctionRelator, Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    functions = relationship('Function', backref='parent')

# subclass `FunctionMixin` to define a Function model
class Function(FunctionMixin, Base):
    __tablename__ = 'function'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey(''))


We can now set the functions attribute to a callable as follows.

def foo(*args, **kwargs):
    print('My args are', args)
    print('My kwargs are', kwargs)
    return 'return value'

parent = Parent()
parent.functions = foo
# equivalent to:
# parent.functions = [foo]
# parent.functions = Function(foo)
# parent.functions = [Function(foo)]


[<__main__.Function object at 0x7f4e5a49c160>]