3.4 KiB
For an advanced programmer new to Python, understanding Python's unique idioms, "Pythonic" ways, and potential gotchas is essential to write efficient, readable, and Pythonic code. Here's a compiled list of Pythonisms, idioms, and gotchas to look out for:
Pythonisms and Idioms
-
List Comprehensions: Compact way to process all or part of the elements in a sequence and return a list with the results.
squares = [x**2 for x in range(10)] -
Dictionary Comprehensions: Similar to list comprehensions but for dictionaries.
square_dict = {x: x**2 for x in range(10)} -
Using Underscore for Unused Variables: It's a Pythonic way to indicate that a variable is intentionally unused.
for _ in range(10): do_something() -
Unpacking: A way to unpack values from a sequence or iterable into variables.
a, b, *rest = range(10) -
The Zen of Python: Accessible by typing
import this, it's a collection of Python's design principles. -
Using
enumerate()for Loops: To get both the index and the value of an item in a list.for index, value in enumerate(my_list): print(index, value) -
Function Arguments: Python supports default, keyword, positional, and arbitrary arguments.
def func(a, b, c=5, *args, **kwargs): pass -
The Walrus Operator (
:=): Introduced in Python 3.8, allows you to assign values to variables as part of an expression.if (n := len(a)) > 10: print(f"List is too long ({n} elements)")
Gotchas
-
Mutable Default Arguments: Default argument values are evaluated only once at function definition time, which means that modifying a default argument will affect all subsequent calls to the function.
def append_to(element, to=[]): to.append(element) return to -
Dynamic Typing: While flexible, it can lead to unexpected behaviors if not carefully managed, especially when coming from statically-typed languages.
-
Indentation: Python uses indentation to define blocks, making code readability a part of the syntax. However, incorrect indentation can lead to
IndentationErroror unexpected behavior. -
==vsis:==checks for equality, whileischecks for identity. This distinction is crucial for understanding mutable and immutable objects.a = [1, 2, 3] b = a print(a == b) # True print(a is b) # True c = a.copy() print(a == c) # True print(a is c) # False -
Looping Pitfalls: Modifying a list while iterating over it can lead to unexpected behavior. Use slicing or create a new list instead.
-
Global vs Local Variables: Variables declared inside a function are local unless explicitly declared global.
-
Floating Point Arithmetic: Like many languages, Python's floating-point numbers can have rounding errors.
print(0.1 + 0.2 == 0.3) # False -
GIL (Global Interpreter Lock): Python's GIL means that only one thread can execute Python bytecodes at a time. This can be a gotcha for CPU-bound multithreading applications.
Understanding these Python-specific idioms and gotchas is crucial for leveraging Python's strengths while avoiding common pitfalls, ensuring your transition to Python is smooth and productive.