title: What's the pythonic way of conditional variable initialization?
body: <p>Due to the scoping rules of Python, all variables once initialized within a scope are available thereafter.  Since conditionals do not introduce new scope, constructs in other languages (such as initializing a variable before that condition) aren't necessarily needed.  For example, we might have:</p>
  
  <pre><code>def foo(optionalvar = None):
      # some processing, resulting in...
      message = get_message()
      if optionalvar is not None:
          # some other processing, resulting in...
          message = get_other_message()
      # ... rest of function that uses message
  </code></pre>
  
  <p>or, we could have instead:</p>
  
  <pre><code>def foo(optionalvar = None):
      if optionalvar is None:
          # processing, resulting in...
          message = get_message()
      else:
          # other processing, resulting in...
          message = get_other_message()
      # ... rest of function that uses message
  </code></pre>
  
  <p>Of course, the <code>get_message</code> and <code>get_other_message</code> functions might be many lines of code and are basically irrelevant (you can assume that the state of the program after each path is the same); the goal here is making <code>message</code> ready for use beyond this section of the function.</p>
  
  <p>I've seen the latter construct used several times in other questions, such as:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/a/6402327/18097">https://stackoverflow.com/a/6402327/18097</a></li>
  <li><a href="https://stackoverflow.com/a/7382688/18097">https://stackoverflow.com/a/7382688/18097</a></li>
  </ul>
  
  <p>Which construct would be more acceptable?</p>