<s> """<STR_LIT>""" <EOL> from sqlalchemy . ext . declarative import as_declarative , declared_attr <EOL> from sqlalchemy import create_engine , Integer , Column , String , ForeignKey <EOL> from sqlalchemy . orm import Session , relationship <EOL> @ as_declarative ( ) <EOL> class Base ( object ) : <EOL> """<STR_LIT>""" <EOL> @ declared_attr <EOL> def __tablename__ ( cls ) : <EOL> return cls . __name__ . lower ( ) <EOL> id = Column ( Integer , primary_key = True ) <EOL> class Address ( object ) : <EOL> """<STR_LIT>""" <EOL> street = Column ( String ) <EOL> city = Column ( String ) <EOL> zip = Column ( String ) <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % ( self . __class__ . __name__ , self . street , <EOL> self . city , self . zip ) <EOL> class HasAddresses ( object ) : <EOL> """<STR_LIT>""" <EOL> @ declared_attr <EOL> def addresses ( cls ) : <EOL> cls . Address = type ( <EOL> "<STR_LIT>" % cls . __name__ , <EOL> ( Address , Base , ) , <EOL> dict ( <EOL> __tablename__ = "<STR_LIT>" % <EOL> cls . __tablename__ , <EOL> parent_id = Column ( Integer , <EOL> ForeignKey ( "<STR_LIT>" % cls . __tablename__ ) ) , <EOL> parent = relationship ( cls ) <EOL> ) <EOL> ) <EOL> return relationship ( cls . Address ) <EOL> class Customer ( HasAddresses , Base ) : <EOL> name = Column ( String ) <EOL> class Supplier ( HasAddresses , Base ) : <EOL> company_name = Column ( String ) <EOL> engine = create_engine ( '<STR_LIT>' , echo = True ) <EOL> Base . metadata . create_all ( engine ) <EOL> session = Session ( engine ) <EOL> session . add_all ( [ <EOL> Customer ( <EOL> name = '<STR_LIT>' , <EOL> addresses = [ <EOL> Customer . Address ( <EOL> street = '<STR_LIT>' , <EOL> city = "<STR_LIT>" , <EOL> zip = "<STR_LIT>" ) , <EOL> Customer . Address ( <EOL> street = '<STR_LIT>' , <EOL> city = "<STR_LIT>" , <EOL> zip = "<STR_LIT>" ) <EOL> ] <EOL> ) , <EOL> Supplier ( <EOL> company_name = "<STR_LIT>" , <EOL> addresses = [ <EOL> Supplier . Address ( <EOL> street = '<STR_LIT>' , <EOL> city = "<STR_LIT>" , <EOL> zip = "<STR_LIT>" ) <EOL> ] <EOL> ) , <EOL> ] ) <EOL> session . commit ( ) <EOL> for customer in session . query ( Customer ) : <EOL> for address in customer . addresses : <EOL> print ( address ) <EOL> print ( address . parent ) </s>
