0

I am reading in some data with try, except blocks (to allow for managed shutdown in case of errors), this often causes Pycharm to read variables as "may be referenced before assignment" as it is apparently incapable of working out that they will either have a value or the function will be exited. e.g.

import sys


def program_exit(code):
    sys.exit(code)


def read_a(input_value):
    try:
        a = input_value
    except:
        program_exit(5)
    a += 1       # referenced before assignment warning
    return a

I know it is possible to block the warning for a specific line but is there any way to tell pycharm that the variable will be defined so that I don't have to block the warning for all subsequent uses of the variable e.g.

import sys


def program_exit(code):
    sys.exit(code)


def read_a(input_value):
    try:
        a = input_value
    except:
        program_exit(5)
    # Pycharm: has_value(a)
    a += 1       # no warning
    return a

Thanks

Pioneer_11
  • 670
  • 4
  • 19

1 Answers1

1

This warning is correct, because in the try block can occur an exception, and the variable can be not defined. I see two ways of solving it:

  1. Defining the variable: You can define the variable as None before the try/catch, so no matter what happens, the variable will always exist.
import sys


def program_exit(code):
    sys.exit(code)


def read_a(input_value):
    a = None
    try:
        a = input_value
    except:
        program_exit(5)
    a += 1 
    return a
  1. Return in the except: PyCharm does not understand that the program_exit function kills the program, but you can add a return after it, the result will be the same, but PyCharm will understand that the except block stops function execution.
import sys


def program_exit(code):
    sys.exit(code)


def read_a(input_value):
    try:
        a = input_value
    except:
        program_exit(5)
        return
    a += 1 
    return a
Rodrigo Llanes
  • 613
  • 2
  • 10
  • The warning is wrong, if the `try` block fails the `except` block executes and the program exits. There is no way for the program to reach `a += 1` without a having a value. While both of your solutions do work I'm not a massive fan of either as anyone who hadn't seen the warning would likely assume it was possible for the function to return `None`. – Pioneer_11 Aug 04 '22 at 11:07