Warning – variable referenced before assignment

Tags: , ,

Having the following snippet:

if use_cache and (cache_data := cache.get(cache_name)) is not None:
       logger.info("Returning objects from Cache")
       return cache_data

I get a Pycharm warning

Local variable cache_data might be used before assignment.

Could you please explain how this could possibly happen in this case or is this an inspection bug?


Unfortunately this seems to be a known issue in PyCharm that was reported back in Nov 2019. It seems the inspection code added to handle assignment expressions doesn’t recognise that the code inside this conditional can only be reached after setting the local variable.

The report notes that it also occurs in comprehension conditionals, and there doesn’t seem to be any fix currently available (or planned).

Source: stackoverflow