title: Python cast string to type if string is not none
body: <p>I have a long list of values to cast and assign. Each value has the possibility of being None. If the value is None, I'd like to leave it as None, otherwise do the casting. The reason being that these values will end up in a database and I will have to convert the None's to NULL's later.</p>
  
  <p>So far the simplest way I've found to do this is by adding inline if statements to each assignment.</p>
  
  <pre><code>self.number = Decimal(input.number) if input.number else None
  </code></pre>
  
  <p>I don't find the code very appealing, it's lacking in readability and it will be tedious to write those statements on for every input value. I would prefer that Decimal(input.number) just return None if input.number is None but that doesn't appear to be the case. Is there a simpler way to do this? I suppose I could make my own Decimal_ function and call that instead?</p>
  
  <hr>
  
  <p>Update:</p>
  
  <p>I've heeded the words of advice hear and come up with this</p>
  
  <pre><code>def dec_(string):
      if string is None:
          return None
      else:
          try:
              return decimal.Decimal(string)
          except:
              return None
  .....
  
  self.number = dec_(input.number)
  </code></pre>
  
  <p>Now I just need to make a cast wrapper for each type of cast I will need to do.</p>
  
  <hr>
  
  <p>Update2:</p>
  
  <p>I think it should work the same by simply running the try block in dec_</p>
  
  <pre><code>def dec_(string):
      try:
          return decimal.Decimal(string)
      except:
          return None
  </code></pre>