Pycharm warns "Local variable <variable> value is not used" in "if" block though it actually used
<p>Pycharm 2016.2 warns me that "Local variable 'message' value is not used" in <code>if</code> block.</p>

<p>Why this?</p>

<pre><code>def build_message(result, action, data, time_stamp, error_message=None, path=None, line=None):
    """
    Result message format:
    Success message format: {'result', 'action', 'target', 'data:{...}', 'timestamp'}
    Failure message format: {'result', 'action', 'error_message', 'path', 'linenumber', 'timestamp', 'data:{}'}
    """
    if result == 'success':
        #  *** I'm getting warning on this one  
        message = {'result': result, 'action': action, 'target': path.strip('\''),
                   'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data}
    else:
        message = {'result': result, 'action': action, 'error_message': error_message,
                   'target': path, 'linenum': line,
                   'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data}
        try:
            return True, json.dumps(message)
        except (ValueError, TypeError) as json_error:
            return False, json_error.message
</code></pre>

<p>Thanks</p>

<p>Your <code>try</code> clause is under <code>else</code> branch so <code>message</code> variable under <code>if</code> branch is never being used.</p>

<p>What you wanted to achieve is probably</p>

<pre><code>if result == 'success':
    #  *** I'm getting warning on this one  
    message = {'result': result, 'action': action, 'target': path.strip('\''),
               'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data}
else:
    message = {'result': result, 'action': action, 'error_message': error_message,
               'target': path, 'linenum': line,
               'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data}
try:
    return True, json.dumps(message)
except (ValueError, TypeError) as json_error:
    return False, json_error.message
</code></pre>

<p>but then you need to get <code>message</code> variable initialized before <code>if-else</code> or you will get errors about using variable before assigning</p>

<pre><code>message = ""
if ...
    ...
else
    ...
</code></pre>

python pycharm