Debian Codegraph @

friendly_traceback/runtime_errors/name_error.py

raw symbols SCIP
1 import re
2 from importlib.util import find_spec
3 from types import FrameType
4 from typing import Any, Tuple
5
6 from .. import debug_helper, info_variables, token_utils, utils
7 from ..ft_gettext import current_lang
8 from ..message_parser import get_parser
9 from ..tb_data import TracebackData # for type checking only
10 from ..typing_info import CauseInfo, SimilarNamesInfo # for type checking only
11 from ..utils import list_to_string
12 from . import stdlib_modules, third_party_names
13 from .modules_attributes import attribute_names
14
15 parser = get_parser(NameError)
16 _ = current_lang.translate
17
18
19 def using_python() -> str: # pragma: no cover
20 return _("You are already using Python!")
21
22
23 # The following is also intended to be used in custom environments;
24 # we currently use it in Mu. It is meant to recognize names that
25 # are intended as a single word command, or call to a function
26 # that does is not available in a given environment.
27 CUSTOM_NAMES = {"python": using_python, "python3": using_python}
28
29
30 def is_module_attribute(name):
31 if name not in attribute_names:
32 return ""
33 names = attribute_names[name]
34 if len(names) == 1:
35 return _(
36 "`{name}` is a name found in module `{mod}`.\n"
37 "Perhaps you forgot to write\n\n from {mod} import {name}\n"
38 ).format(name=name, mod=names[0])
39 return _(
40 "`{name}` is a name found in the following modules:\n"
41 "{modules}.\n"
42 "Perhaps you forgot to import `{name}` from one of these modules.\n"
43 ).format(name=name, modules=list_to_string(names))
44
45
46 @parser._add
47 def free_variable_referenced(message: str, _tb_data: TracebackData) -> CauseInfo:
48 pattern = re.compile(
49 r"free variable '(.*)' referenced before assignment in enclosing scope"
50 )
51 pattern3_11 = re.compile(
52 r"cannot access free variable '(.*)'"
53 + " where it is not associated with a value in enclosing scope"
54 )
55 match = re.search(pattern, message)
56 if not match:
57 match = re.search(pattern3_11, message)
58 if not match:
59 return {}
60
61 unknown_name = match[1]
62 cause = _(
63 "In your program, `{var_name}` is an unknown name\n"
64 "that exists in an enclosing scope,\n"
65 "but has not yet been assigned a value.\n"
66 ).format(var_name=unknown_name)
67 return {"cause": cause}
68
69
70 @parser._add
71 def name_not_defined(message: str, tb_data: TracebackData) -> CauseInfo:
72 pattern = re.compile(r"name '(.*)' is not defined")
73 match = re.search(pattern, message)
74 if not match:
75 return {}
76
77 unknown_name = match[1]
78 frame = tb_data.exception_frame
79 is_special_name = perhaps_special_name(unknown_name, tb_data)
80 if is_special_name:
81 return is_special_name
82
83 is_special_keyword = perhaps_special_keyword(
84 unknown_name, tb_data.original_bad_line
85 )
86 if is_special_keyword:
87 return is_special_keyword
88
89 cause = _("In your program, no object with the name `{var_name}` exists.\n").format(
90 var_name=unknown_name
91 )
92
93 # If the unknown name is followed by '.', it is not a typo for a builtin
94 potential_module_attribute = "<None>"
95 try:
96 rest_of_line = tb_data.node.first_token.line[tb_data.node.first_token.end[1] :]
97 tokens = token_utils.get_significant_tokens(rest_of_line)
98 potential_module = tokens and tokens[0].string == "."
99 if len(tokens) > 1:
100 potential_module_attribute = tokens[1].string
101 except Exception: # noqa
102 potential_module = True
103 similar = info_variables.get_similar_names(unknown_name, frame)
104 else:
105 similar = info_variables.get_similar_names(
106 unknown_name, frame, include_builtins=not potential_module
107 )
108
109 hint = ""
110 if potential_module:
111 known_module = is_stdlib_module(unknown_name)
112 if known_module:
113 cause = known_module["cause"]
114 if "suggest" in hint:
115 hint = known_module["suggest"]
116 else:
117 known_module = is_third_party_module(unknown_name)
118 if known_module:
119 cause = known_module["cause"]
120 hint = known_module["suggest"]
121
122 type_hint = info_variables.name_has_type_hint(unknown_name, frame)
123
124 if similar["best"]:
125 if hint:
126 hint = hint.replace("\n", "") + _(" Or did you mean `{name}`?\n").format(
127 name=similar["best"]
128 )
129 else:
130 hint = _("Did you mean `{name}`?\n").format(name=similar["best"])
131 elif type_hint and not hint:
132 hint = _("Did you use a colon instead of an equal sign?\n")
133
134 additional = type_hint + format_similar_names(unknown_name, similar)
135 try:
136 more, hint = missing_self(unknown_name, frame, tb_data, hint)
137 if more:
138 additional += "\n" + more
139 except Exception as e: # pragma: no cover
140 debug_helper.log("Problem in name_not_defined()/missing_self().")
141 debug_helper.log_error(e)
142
143 forgot_import = is_module_attribute(unknown_name)
144 if forgot_import:
145 if additional:
146 additional += "\n" + forgot_import
147 else:
148 additional = forgot_import
149 if not additional and not hint:
150 # example: maths.pi
151 name = typo_in_stdlib_module(unknown_name, potential_module_attribute)
152 if name:
153 additional = "\n" + _(
154 "Perhaps you meant to write `{name}` and also forgot to import it.\n"
155 ).format(name=name)
156 else:
157 additional = _("I have no additional information for you.\n")
158
159 explanation = {"cause": cause + additional}
160 if not hint:
161 return explanation
162 explanation["suggest"] = hint
163 return explanation
164
165
166 def perhaps_special_name(name: str, tb_data: TracebackData) -> CauseInfo:
167 if name == "ꓺ": # pragma: no cover
168 return flipfloperator()
169 if name == "__debug__" and tb_data.bad_line.startswith("del "):
170 return delete_debug()
171 if name in {"i", "j"}:
172 hint = _("Did you mean `1j`?\n")
173 cause = _(
174 "In your program, no object with the name `{var_name}` exists.\n"
175 ).format(var_name=name)
176 cause += _(
177 "However, sometimes `{name}` is intended to represent\n"
178 "the square root of `-1` which is written as `1j` in Python.\n"
179 ).format(name=name)
180 return {"cause": cause, "suggest": hint}
181 if name in CUSTOM_NAMES:
182 bad_line = tb_data.bad_line.replace("(", "").replace(")", "").strip()
183 if bad_line == name:
184 cause = CUSTOM_NAMES[name]()
185 return {"cause": cause, "suggest": cause}
186 return {}
187
188
189 def perhaps_special_keyword(word_with_typo: str, bad_line: str) -> CauseInfo:
190 """Identifies if one of 'pass', 'break', and 'continue' has possibly been misspelled.
191 For 'break' and 'continue', it verifies that it would be used on an indented line since
192 not doing so would definitely result in a SyntaxError.
193 """
194 tokens = token_utils.get_significant_tokens(bad_line)
195 if len(tokens) != 1:
196 return {}
197 token = tokens[0]
198 similar = utils.get_similar_words(word_with_typo, ["pass", "continue", "break"])
199 if not similar:
200 return {}
201 correct_word = similar[0]
202 if correct_word in ["continue", "break"] and token.start_col == 0:
203 # continue and break need to be part of a block. We do not want
204 # to make a suggestion that would result in a SyntaxError
205 return {}
206 hint = _("Did you mean `{word}`?\n").format(word=correct_word)
207 cause = _(
208 "I suspect you meant to write the keyword `{word}` and made a typo.\n"
209 ).format(word=correct_word)
210 return {"cause": cause, "suggest": hint}
211
212
213 def delete_debug() -> CauseInfo:
214 # https://bugs.python.org/issue45000
215 hint = _("`__debug__` is a constant.\n")
216 cause = _(
217 "`__debug__` is a constant that cannot be deleted.\n"
218 "In future Python versions, attempting to delete it will be a SyntaxError.\n"
219 )
220 return {"cause": cause, "suggest": hint}
221
222
223 def flipfloperator() -> CauseInfo: # pragma: no cover
224 hint = _("You must be a fan of PyConAu!\n")
225 cause = _(
226 "I am guessing that you tried to use (one of) the flipfloperators\n"
227 "shown during the second Lightning Talk session of PyConAu 2018,\n"
228 "but that you forgot to install the module from PyPI.\n\n"
229 "#### Note that it is still a bad idea.\n"
230 )
231 return {"cause": cause, "suggest": hint}
232
233
234 def is_stdlib_module(name: str) -> CauseInfo:
235 """Determine if an unknown name is to be found in the Python standard library.
236 We're looking for something like name.attribute"""
237 # Some Python 2 libraries used names with uppercase letters.
238 lowercase = name.lower()
239 if stdlib_modules.module_exists(name) or stdlib_modules.module_exists(lowercase):
240 hint = _("Did you forget to import `{name}`?\n").format(name=lowercase)
241 cause = (
242 "\n"
243 + _(
244 "The name `{name}` is not defined in your program.\n"
245 "Perhaps you forgot to import `{lowercase}` which is found\n"
246 "in Python's standard library.\n"
247 ).format(name=name, lowercase=lowercase)
248 + "\n"
249 )
250 if name != lowercase:
251 cause += (
252 _(
253 "Note that the name of the module is `{lowercase}` and not `{name}`.\n"
254 ).format(lowercase=lowercase, name=name)
255 + "\n"
256 )
257 return {"cause": cause, "suggest": hint, "lowercase": True}
258 return {"cause": cause, "suggest": hint}
259 if name in stdlib_modules.names:
260 return {
261 "cause": _(
262 "There is a module named `{name}` that is part of the\n"
263 "Python standard library. However, it might not be available\n"
264 "for your operating system, or it may to be installed separately.\n"
265 ).format(name=name)
266 + "\n\n"
267 }
268 return {}
269
270
271 def typo_in_stdlib_module(name, attribute):
272 similar = utils.get_similar_words(name, stdlib_modules.names)
273 for other in similar:
274 if (
275 stdlib_modules.module_exists(other)
276 and attribute in attribute_names
277 and other in attribute_names[attribute]
278 ):
279 return other
280 return None
281
282
283 def is_third_party_module(name: str) -> CauseInfo:
284 found = find_spec(name)
285 if found:
286 hint = _("Did you forget to import `{name}`?\n").format(name=name)
287 cause = (
288 "\n"
289 + _(
290 "The name `{name}` is not defined in your program.\n"
291 "Perhaps you forgot to import `{name}` which is a known library.\n"
292 ).format(name=name)
293 + "\n"
294 )
295 return {"cause": cause, "suggest": hint}
296
297 synonyms = third_party_names.module_synonyms
298 if name in synonyms:
299 hint = _("Did you forget to import `{true_name}`?\n").format(
300 true_name=synonyms[name]
301 )
302 cause = (
303 "\n"
304 + _(
305 "The name `{name}` is not defined in your program.\n"
306 "Perhaps you forgot to write\n\n"
307 " import {true_name} as {name}\n"
308 ).format(name=name, true_name=synonyms[name])
309 + "\n"
310 )
311 return {"cause": cause, "suggest": hint}
312 return {}
313
314
315 def format_similar_names(name: str, similar: SimilarNamesInfo) -> str:
316 """This function formats the names that were found to be similar"""
317 nb_similar_names = (
318 len(similar["locals"]) + len(similar["globals"]) + len(similar["builtins"])
319 )
320 if nb_similar_names == 0:
321 return ""
322
323 found_local = _("The similar name `{name}` was found in the local scope.\n")
324 found_global = _("The similar name `{name}` was found in the global scope.\n")
325 builtin_similar = _("The Python builtin `{name}` has a similar name.\n")
326
327 if nb_similar_names == 1:
328 if similar["locals"]:
329 return found_local.format(name=similar["locals"][0])
330 if similar["globals"]:
331 return found_global.format(name=similar["globals"][0])
332 return builtin_similar.format(name=similar["builtins"][0])
333
334 message = _(
335 "Instead of writing `{name}`, perhaps you meant one of the following:\n"
336 ).format(name=name)
337
338 for scope, pre in (
339 ("locals", _("* Local scope: ")),
340 ("globals", _("* Global scope: ")),
341 ("builtins", _("* Python builtins: ")),
342 ):
343 if similar[scope]:
344 message += pre + str(similar[scope])[1:-1].replace("'", "`") + "\n"
345
346 return message
347
348
349 def missing_self(
350 unknown_name: str, frame: FrameType, tb_data: TracebackData, hint: str
351 ) -> Tuple[str, str]:
352 """If the unknown name is referred to with no '.' before it,
353 and is an attribute of a known object, perhaps 'self.'
354 is missing."""
355 message = ""
356 try:
357 bad_statement = utils.get_bad_statement(tb_data)
358 tokens = token_utils.get_significant_tokens(bad_statement)
359 except Exception: # noqa # pragma: no cover
360 debug_helper.log(
361 "Exception raised in missing_self() while trying to get tokens"
362 )
363 return message, hint
364
365 if not tokens: # pragma: no cover
366 return message, hint
367
368 prev_token = tokens[0]
369 for index, token in enumerate(tokens):
370 if token == unknown_name and prev_token != ".":
371 break
372 prev_token = token
373 else:
374 return message, hint
375
376 first_arg_self = (
377 len(tokens) > index + 3
378 and tokens[index + 1] == "("
379 and tokens[index + 2] == "self"
380 )
381
382 env = (("local", frame.f_locals), ("global", frame.f_globals))
383
384 for scope, dict_ in env:
385 names = info_variables.get_variables_in_frame_by_scope(frame, scope)
386 dict_copy = dict(dict_)
387 for name in names:
388 if name in dict_copy:
389 obj = dict_copy[name]
390 known_attributes = dir(obj)
391 if unknown_name in known_attributes:
392 return missing_self_cause(
393 name, unknown_name, obj, scope, first_arg_self, hint
394 )
395 return message, hint
396
397
398 def missing_self_cause(
399 name: str, unknown_name: str, obj: Any, scope: str, first_arg_self: bool, hint: str
400 ) -> Tuple[str, str]:
401 obj_repr = repr(obj)
402 if obj_repr.startswith("<") and obj_repr.endswith(">"):
403 obj_repr = info_variables.simplify_repr(obj_repr, splitlines=False)
404 if first_arg_self and name == "self":
405 suggest = _("Did you write `self` at the wrong place?\n")
406 message = _(
407 "The {scope} object `{obj}`\n"
408 "has an attribute named `{unknown_name}`.\n"
409 "Perhaps you should have written `self.{unknown_name}(...`\n"
410 "instead of `{unknown_name}(self, ...`.\n"
411 ).format(scope=scope, obj=obj_repr, unknown_name=unknown_name)
412 elif name == "self":
413 suggest = _("Did you forget to add `self.`?\n")
414 message = _(
415 "A {scope} object, `{obj}`,\n"
416 "has an attribute named `{unknown_name}`.\n"
417 "Perhaps you should have written `self.{unknown_name}`\n"
418 "instead of `{unknown_name}`.\n"
419 ).format(scope=scope, obj=obj_repr, unknown_name=unknown_name)
420 else:
421 suggest = _("Did you forget to add `{name}.`?\n").format(name=name)
422 message = _(
423 "The {scope} object `{name}`\n"
424 "has an attribute named `{unknown_name}`.\n"
425 "Perhaps you should have written `{name}.{unknown_name}`\n"
426 "instead of `{unknown_name}`.\n"
427 ).format(scope=scope, name=name, unknown_name=unknown_name)
428
429 hint += suggest
430 return message, hint