Search code examples
pythonpycharm

try: VAR = ... except: VAR = ... finally: VAR - Local variable 'VAR' might be referenced before assignment


Why is PyCharm warning me that streamer might be referenced before assignment? In my opinion, all the situations are covered by try or except block so in finally block the streamer is always defined.

    try:
        streamer = Streamer.objects.get(user_id=self.user_id)
    except Streamer.DoesNotExist:
        streamer = Streamer.objects.create(**streamer_attrs)
    except:
        streamer = Streamer.objects.create(**streamer_attrs)
    finally:
        for fieldname, value in streamer_attrs:
            setattr(streamer, fieldname, value)

enter image description here

Is there a reason behind this warning?


Solution

  • If the assignment in your except section throws an exception as well (and it may):

    except:
        streamer = Streamer.objects.create(**streamer_attrs)
    

    .. then the finally block still gets executed, but streamer won't be defined. I think the issue is you didn't realise that a finally gets executed even when an exception occurs?

    The only times a finally won't run is if the thread or process that has the block is killed beforehand, you exited the program (using exit()) or something underlying fails (like the OS, VM, container, etc.)