title: SqlAlchemy: Refer to the bound session from an object?
body: <p>Suppose I am using a declarative object like the following:</p>
  
  <pre><code>class MyObject(DeclarativeBase):
     ...
     other_object_id = Column(Integer, ForeignKey('other_object.id'))
     other_object = relationship("OtherObject")
     ...
  </code></pre>
  
  <p>Suppose I would like to have a convenience method <code>set_other_object_value</code>, which would modify <code>other_object.value</code>, <em>creating</em> an instance of <code>OtherObject</code> and adding it to the session, if necessary:</p>
  
  <pre><code>def set_other_object_value(self, value):
     if self.other_object is None:
        &lt;create instance of OtherObject and associate with the session&gt;
     self.other_object.value = value
  </code></pre>
  
  <p>The question is: how can I create <code>OtherObject</code> and associate it with the session? A possibly equivalent question: is it possible to access the instance of a <code>Session</code>, to which <code>MyObject</code> was added from within an instance of <code>MyObject</code>?</p>