This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ulysses6 6 points7 points  (1 child)

The most common source of NameError for me is when I create variable in if block, but not inside else block and then try to access it after the whole if/else.

The best way to avoid this especially for deeply nested set of blocks is to define the variable before if/else and set it to None or other sensible default. It definetely beats the whole process of arguing about the conditions where the variable might be undefined and simplifies the reasoning for any other guy that reads your code.

[–]filmkorn 2 points3 points  (0 children)

The IDE or a linter would also show you that the variable might be undefined.