title: Best practice for handling class fields that require a server call
body: <p>I have a class field that I want to assign the result of a dependency call to.
  Where is the best place to do the dependency call, an HTTP call to a server, and assign the result?</p>
  <p>Take this class for example:</p>
  <pre class="lang-py prettyprint-override"><code>@dataclass
  class User:
      id: str
      username: str = &quot;&quot; # Unknown at initialization stage, requires http call to get username based in id
  </code></pre>
  <p>In this context:</p>
  <pre class="lang-py prettyprint-override"><code>user = User(id='12345')
  result = dummy_library.get_username(user.id) # call to a server and return result
  user.username = result.username
  </code></pre>
  <p>I have a few options in mind, however, I'm unable to come to a decision on which one to use:</p>
  <h3>Option 1: Assign <code>username</code> in a try/except in <code>__init__</code></h3>
  <p>Pros:</p>
  <ul>
  <li>Simple</li>
  </ul>
  <p>Cons:</p>
  <ul>
  <li>Hard to test, need to inject the <code>dummy_library</code> into class to call it</li>
  </ul>
  <h3>Option 2: Assign <code>username</code> in a try/except in <code>__post_init__</code></h3>
  <p>Same as Option 1, except shifting work to <strong>post_init</strong></p>
  <h3>Option 3: Assign <code>username</code> in an instance function</h3>
  <pre class="lang-py prettyprint-override"><code>class User:
  ...
      def set_username(self, dummy_library):
          try:
              result = dummy_library.get_username(user.id) # call to a server and return result
              user.username = result.username
          except:
              ...
  ...
  user = User(id='12345')
  user.set_username(dummy_library)
  </code></pre>
  <p>Pros:</p>
  <ul>
  <li>Easy to unit test with dependency injection</li>
  </ul>
  <p>Cons:</p>
  <ul>
  <li>Redundant, must call <code>set_username</code> after each <code>User</code> instantiation</li>
  </ul>
  <h3>Option 4: Get <code>username</code> before initializing <code>User</code></h3>
  <pre class="lang-py prettyprint-override"><code>try:
      user_id = '12345'
      result = dummy_library.get_username(id=user_id) # call to a server and return result
      user = User(id=user_id, username=result.username)
  except:
      ...
  </code></pre>
  <p>Pros:</p>
  <ul>
  <li>Easy to unit test with dependency injection</li>
  </ul>
  <p>Cons:</p>
  <ul>
  <li>Redundant, try/except for each User instantiation</li>
  </ul>