Python common mistakes
by Ty Myrddin
Updated on May 4, 2022
For now, just a list, and we expect to encounter these. We will return to this post whenever we do to update it with examples.
- Misusing expressions as defaults for function arguments
- Using class variables incorrectly - Class variables are internally handled as dictionaries and follow Method Resolution Order (MRO)
- Specifying parameters incorrectly for an exception block - The proper way to catch multiple exceptions in an except statement is to specify the first parameter as a tuple containing all exceptions to be caught.
- Misunderstanding Python scope rules - Python scope resolution is based on what is known as the LEGB rule,
which is shorthand for Local, Enclosing, Global, Built-in. Especially with lists, tricky.
UnboundLocalError
- Modifying a list while iterating over it - List comprehensions are particularly useful for avoiding this specific problem
- Confusing how Python binds variables in closures - Python’s late binding behavior says that the values of variables used in closures are looked up at the time the inner function is called.
>>> def create_multipliers():
... return [lambda x : i * x for i in range(5)]
>>> for multiplier in create_multipliers():
... print multiplier(2)
...
8
8
8
8
8
The solution to this common Python problem is a bit of a hack:
>>> def create_multipliers():
... return [lambda x, i=i : i * x for i in range(5)]
...
>>> for multiplier in create_multipliers():
... print multiplier(2)
...
0
2
4
6
8
- Creating circular module dependencies
- Name clashing with Python Standard Library modules
- Misusing the __del__ method
...
WHERE'S MY COW?! Wyrd Sisters