title: 'NoneType' object has no attribute, reference class variable declared before __init__
body: <p>I am using Flask with SQLAlchemy to create a 1-to-1 relationship between a Search request and parsed Data. Once a user has checked over the search results, they can click continue to parse the data (and create a Data class instance). However, I am unsure how to reference class variables before an <code>__init__</code> reference. I want my <code>Data</code> instance to have a requests response object <code>r</code>.</p>
  
  <p>Calling code (views.py):</p>
  
  <pre><code>search = Search(form)  # create source result
  search.author = g.user
  db.session.add(search)
  db.session.commit()
  
  ...
  
  data = Data()
  data.search_id = this_search.id
  db.session.add(data)
  db.session.commit()
  </code></pre>
  
  <p>Search class (models.py):</p>
  
  <pre><code>class Search(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      timestamp = db.Column(db.DateTime)
      user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
  
      data_id = db.relationship('Data', backref='source', lazy='dynamic')
      ...
  </code></pre>
  
  <p>Data class (models.py):</p>
  
  <pre><code>class Data(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      search_id = db.Column(db.Integer, db.ForeignKey('search.id'))
      search = db.relationship('Search', backref="information")
      r = None
  
      def __init__(self):
          self.r = requests.get(self.search.url)
  </code></pre>
  
  <p>The error I get is: </p>
  
  <blockquote>
    <p>AttributeError: 'NoneType' object has no attribute 'url'</p>
  </blockquote>
  
  <p>It is clear that I cannot create <code>self.r</code> before the <code>Data.search</code> variable is declared, since the error suggests that it is <code>NoneType</code> type. I am not sure what the proper format creating new variables like this should be. The code works if I move the <code>self.r</code> declaration to a class method that is called after initialization. Thanks!</p>