What common mistakes do developers make when writing code and how to avoid them?
sobes.tech AI
Answer from AI
Common mistakes when writing Python code and how to avoid them:
-
Indentation errors: Python is sensitive to indentation; incorrect alignment leads to SyntaxError. Use a consistent style of indentation (spaces or tabs) and configure your editor.
-
Modifying mutable default arguments in functions: Using mutable objects (like lists) as default values can lead to unexpected behavior. It's better to use
Noneand create the object inside the function. -
Uncaught exceptions: Lack of error handling can cause the program to crash. Use
try-exceptblocks to handle expected errors. -
Incorrect use of variables and scope: Confusion between local and global variables can cause errors. Watch the scope and use
globalornonlocalwhen necessary. -
Poor variable naming: Unclear names make code harder to read. Use meaningful and descriptive names.
-
Ignoring documentation and comments: Without comments and documentation, code becomes difficult to maintain.
-
Suboptimal use of data structures: For example, using a list where a set or dictionary would be more appropriate.
To avoid errors, it is recommended to:
- Write tests
- Use static code analyzers (e.g., pylint, flake8)
- Follow PEP 8 — the official Python style guide
- Conduct code reviews
Example of an error with a mutable default argument:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] — unexpected!
Correct version:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [2]