| 1 |
import re |
| 2 |
|
| 3 |
from .. import info_variables, token_utils |
| 4 |
from ..ft_gettext import current_lang |
| 5 |
from ..message_parser import get_parser |
| 6 |
from ..tb_data import TracebackData |
| 7 |
from ..typing_info import CauseInfo |
| 8 |
|
| 9 |
parser = get_parser(RuntimeError) |
| 10 |
_ = current_lang.translate |
| 11 |
|
| 12 |
|
| 13 |
@parser._add |
| 14 |
def container_changed_size_during_iteration( |
| 15 |
message: str, tb_data: TracebackData |
| 16 |
) -> CauseInfo: |
| 17 |
pattern = re.compile(r"(.*) changed size during iteration") |
| 18 |
match = re.search(pattern, message) |
| 19 |
if not match: |
| 20 |
return {} |
| 21 |
container_name = match[1].lower() |
| 22 |
frame = tb_data.exception_frame |
| 23 |
if container_name.startswith("dict"): |
| 24 |
container_name = "dict" |
| 25 |
obj_type = dict |
| 26 |
elif container_name == "set": |
| 27 |
obj_type = set |
| 28 |
else: |
| 29 |
return {} |
| 30 |
container_type = info_variables.convert_type(container_name) |
| 31 |
|
| 32 |
objects = info_variables.get_all_objects(tb_data.bad_line, frame) |
| 33 |
names = [] |
| 34 |
for name, obj in objects["name, obj"]: |
| 35 |
if isinstance(obj, obj_type): |
| 36 |
names.append(name) |
| 37 |
|
| 38 |
tokens = token_utils.tokenize(tb_data.bad_line) |
| 39 |
loop_keywords = [tok.string for tok in tokens if tok.string in {"for", "while"}] |
| 40 |
|
| 41 |
loop_keywords = set(loop_keywords) |
| 42 |
if len(loop_keywords) == 1: |
| 43 |
for_while = "for" if "for" in loop_keywords else "while" |
| 44 |
else: |
| 45 |
for_while = "for/while" |
| 46 |
|
| 47 |
if len(names) == 1: |
| 48 |
cause = _( |
| 49 |
"While you were iterating over the items of `{name}` ({container_type})\n" |
| 50 |
"in a `{for_while}` loop, you either tried to add or remove items from it.\n" |
| 51 |
"Suggestion: start by making a copy of `{name}` and iterate over the items\n" |
| 52 |
"of that copy if you want to change `{name}` inside a loop.\n" |
| 53 |
"You might want to do this as follows:\n\n" |
| 54 |
" my_{name} = {name}.copy()\n" |
| 55 |
" for item in my_{name}:\n" |
| 56 |
" # Change {name}\n" |
| 57 |
).format(name=names[0], container_type=container_type, for_while=for_while) |
| 58 |
else: |
| 59 |
cause = _( |
| 60 |
"While you were iterating over the items of a container ({container_type})\n" |
| 61 |
"in a `{for_while}` loop, you either tried to add or remove items from it.\n" |
| 62 |
"Suggestion: start by making a copy of the container and iterate over the items\n" |
| 63 |
"of that copy if you want to change that container inside a loop.\n" |
| 64 |
).format(container_type=container_type, for_while=for_while) |
| 65 |
|
| 66 |
return {"cause": cause} |