classification
Title: operator |= on sets does not behave like the update method
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.8, Python 3.7, Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Gabriele Tornetta, ammar2
Priority: normal Keywords:

Created on 2020-01-31 10:30 by Gabriele Tornetta, last changed 2020-01-31 10:46 by ammar2. This issue is now closed.

Messages (2)
msg361097 - (view) Author: Gabriele N Tornetta (Gabriele Tornetta) * Date: 2020-01-31 10:30
def outer():
  a=set()
  def inner():
    a |= set(["A"])
  inner()
  return a

print(outer())

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print(outer())
  File "main.py", line 5, in outer
    inner()
  File "main.py", line 4, in inner
    a |= set(["A"])
UnboundLocalError: local variable 'a' referenced before assignment

However, the update method works as expected:

def outer():
  a=set()
  def inner():
    a.update(set(["A"]))
  inner()
  return a

print(outer())

{'A'}
msg361099 - (view) Author: Ammar Askar (ammar2) * (Python committer) Date: 2020-01-31 10:46
Take a look at https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

What's happening is that because `a |= x` is treated as an assignment, i.e `a = a | x`. The compiler treats it as a local variable, but since it hasn't been initialized in inner() before it reaches `a |= set(["A"])` it fails with UnboundLocalError.
History
Date User Action Args
2020-01-31 10:46:09ammar2setstatus: open -> closed

nosy: + ammar2
messages: + msg361099

resolution: not a bug
stage: resolved
2020-01-31 10:30:54Gabriele Tornettacreate