Python Code Smells

Common code smells in Python and how to fix them.


Mutable Default Arguments

 1# ❌ Bad: Mutable default argument
 2def append_to_list(item, my_list=[]):
 3    my_list.append(item)
 4    return my_list
 5
 6print(append_to_list(1))  # [1]
 7print(append_to_list(2))  # [1, 2] - Unexpected!
 8
 9# βœ… Good: Use None as default
10def append_to_list(item, my_list=None):
11    if my_list is None:
12        my_list = []
13    my_list.append(item)
14    return my_list

Bare Except

 1# ❌ Bad: Catches everything including KeyboardInterrupt
 2try:
 3    risky_operation()
 4except:
 5    pass
 6
 7# βœ… Good: Catch specific exceptions
 8try:
 9    risky_operation()
10except (ValueError, TypeError) as e:
11    logger.error(f"Operation failed: {e}")
12    raise

Using is for Value Comparison

 1# ❌ Bad: Using 'is' for value comparison
 2if x is True:
 3    pass
 4
 5if name is "John":
 6    pass
 7
 8# βœ… Good: Use == for values
 9if x:  # or if x == True:
10    pass
11
12if name == "John":
13    pass
14
15# βœ… Correct use of 'is'
16if x is None:
17    pass

Not Using List Comprehensions

1# ❌ Bad: Verbose loop
2squares = []
3for i in range(10):
4    squares.append(i ** 2)
5
6# βœ… Good: List comprehension
7squares = [i ** 2 for i in range(10)]

String Concatenation in Loops

1# ❌ Bad: Inefficient
2result = ""
3for item in items:
4    result += str(item) + ","
5
6# βœ… Good: Use join
7result = ",".join(str(item) for item in items)

Not Using Context Managers

 1# ❌ Bad: Manual resource management
 2file = open('file.txt')
 3try:
 4    data = file.read()
 5finally:
 6    file.close()
 7
 8# βœ… Good: Context manager
 9with open('file.txt') as file:
10    data = file.read()

Not Using get() for Dictionaries

1# ❌ Bad: KeyError risk
2value = my_dict['key']
3
4# βœ… Good: Use get with default
5value = my_dict.get('key', default_value)

Using list as Variable Name

1# ❌ Bad: Shadows built-in
2list = [1, 2, 3]
3
4# βœ… Good: Use descriptive name
5items = [1, 2, 3]

Related Snippets

  • C/C++ Code Smells
    Common code smells in C/C++ and how to fix them. Memory Leaks 1// ❌ Bad 2void …
  • C/C++ Secure Coding
    Secure coding practices for C/C++ applications. Buffer Overflow Prevention 1// ❌ …
  • C/C++ Vulnerability Checks
    Tools for checking vulnerabilities in C/C++ code. Valgrind 1# Install 2sudo apt …
  • Common Antipatterns
    Common software antipatterns to avoid across all languages and architectures. …
  • Common Code Smells
    Common code smells to watch for during code reviews with examples and fixes. …
  • Developer Pre-Submission Checklist
    Comprehensive checklist for developers before submitting a pull request. Code …
  • Go Code Smells
    Common code smells in Go and how to fix them. Ignoring Errors 1// ❌ Bad 2result, …
  • Go Secure Coding
    Secure coding practices for Go applications. SQL Injection Prevention 1// ❌ …
  • Go Vulnerability Checks
    Tools for checking vulnerabilities in Go code. Govulncheck 1# Install 2go …
  • Haskell Code Smells
    Common code smells in Haskell and how to fix them. Partial Functions 1-- ❌ Bad: …
  • Haskell Secure Coding
    Secure coding practices for Haskell applications. SQL Injection Prevention 1-- ❌ …
  • Haskell Vulnerability Checks
    Tools for checking vulnerabilities in Haskell code. Cabal Outdated 1# Check …
  • Python Secure Coding
    Secure coding practices for Python applications. SQL Injection Prevention 1# ❌ …
  • Python Vulnerability Checks
    Tools for checking vulnerabilities in Python code. Safety - Dependency Scanner …
  • Reviewer Checklist
    Comprehensive checklist for code reviewers to ensure thorough and constructive …
  • Rust Code Smells
    Common code smells in Rust and how to fix them. Unwrap/Expect Abuse 1// ❌ Bad …
  • Rust Secure Coding
    Secure coding practices for Rust applications. SQL Injection Prevention 1// ❌ …
  • Rust Vulnerability Checks
    Tools for checking vulnerabilities in Rust code. Cargo Audit 1# Install 2cargo …
  • TypeScript Code Smells
    Common code smells in TypeScript and how to fix them. Using any 1// ❌ Bad …
  • TypeScript Secure Coding
    Secure coding practices for TypeScript applications. XSS Prevention 1// ❌ …
  • TypeScript Vulnerability Checks
    Tools for checking vulnerabilities in TypeScript/JavaScript code. npm audit 1# …