E:\PyStudy\cpython>.\python.bat -m test.py -j3
Running Debug|x64 interpreter...
Traceback (most recent call last):
File "E:\PyStudy\cpython\Lib\runpy.py", line 189, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\PyStudy\cpython\Lib\runpy.py", line 112, in _get_module_details
__import__(pkg_name)
File "E:\PyStudy\cpython\test.py", line 18, in <module>
test4(1)
File "E:\PyStudy\cpython\test.py", line 13, in test4
ls += [element]
^^
UnboundLocalError: cannot access local variable 'ls' where it is not associated with a value
I don’t know why the error happened,I checked the official documentation, which says that the effect of extend() and += should be the same.
The difference from the other test functions is that here you are referring to ls in an “assignment context”. left of = or here +=, so Python will create a local variable, which is not initialised when you first read it.
Be sure to note that if an assignment is made to a name within a function, that name is considered to be local throughout the function, unless it is declared otherwise. This applies even where the name appears in statements that precede the first assignment to it within that function.
Here is an example:
ls = []
def test4(element):
print(ls)
ls += [element]
test4(1)
Part of the error message:
line 4, in test4
print(ls)
UnboundLocalError: cannot access local variable 'ls' where it is not associated with a value
In this case, it was the passing of ls to the print function that raised the error, because even though that preceded the assignment, the name ls was considered local throughout the function.