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