Samuel
Samuel

Reputation: 3801

Pycharm warns "Local variable <variable> value is not used" in "if" block though it actually used

Pycharm 2016.2 warns me that "Local variable 'message' value is not used" in if block.

Why this?

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

Thanks

Upvotes: 0

Views: 1198

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13571

Your try clause is under else branch so message variable under if branch is never being used.

What you wanted to achieve is probably

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

but then you need to get message variable initialized before if-else or you will get errors about using variable before assigning

message = ""
if ...
    ...
else
    ...

Upvotes: 4

Related Questions