Avoid using spaces around operators (e.g., +, -, *, /) unless they are necessary for clarity or readability. For example, x = y + z is preferred over x=y+z. However, if the expression becomes too long and difficult to read, you can use parentheses to group parts of it together: (x * 2) ** 3
2. Use indentation consistently for all blocks of code within functions or loops. This will help prevent errors caused by accidentally mixing up different block structures. For example, if you have a function with multiple lines inside an “if” statement, make sure that the indents are consistent:
def my_function():
x = 10
if x > 5:
y = x * 2
print(y)
3. Use comments to explain complex or confusing code. This will help other programmers (or future versions of yourself!) understand what the code is doing and why it’s necessary. For example, you might add a comment like this:
# Calculate the sum of all even numbers in a list
def calculate_sum(numbers):
total = 0
for num in numbers:
if num % 2 == 0:
total += num
4. Use meaningful variable names that accurately describe what they represent. This will help other programmers (or future versions of yourself!) understand the code more easily and avoid errors caused by misunderstanding or confusion. For example, instead of using “x” to store a list of numbers, you might use something like “numbers_list”.
5. Use whitespace liberally to make your code easier to read and follow. This will help prevent errors caused by accidentally mixing up different block structures or confusing syntax. For example:
def my_function():
x = 10
if x > 5:
y = x * 2
print(y)
6. Use the “with” statement to manage resources that need to be opened and closed, such as files or database connections. This will help prevent errors caused by forgetting to close these resources properly. For example:
with open(‘my_file.txt’, ‘r’) as f:
for line in f:
# do something with each line of text
7. Use the “try-except” statement to handle exceptions that might occur during program execution, such as a file not being found or an invalid input value. This will help prevent errors caused by unexpected behavior and make your code more robust. For example:
def my_function():
try:
x = int(input(“Enter a number: “))
if x > 5:
y = x * 2
print(y)
except ValueError:
print(“Invalid input. Please enter an integer.”)
8. Use the “pass” statement to indicate that you’re intentionally doing nothing in a block of code, such as inside an empty function or loop body. This will help prevent errors caused by accidentally forgetting to add something there later on. For example:
def my_function():
pass
9. Avoid using global variables unless absolutely necessary, as this can cause conflicts and errors with other parts of your code. Instead, use local variables whenever possible to help prevent these issues. For example:
def my_function():
x = 5
# do something here that uses the variable “x”
10. Use the “isinstance()” function to check whether an object is of a certain type or class, which can help prevent errors caused by accidentally using the wrong data type in your code. For example:
if isinstance(obj, int):
# do something here if obj is an integer
11. Use the “is” and “is not” operators to check whether two objects are (or aren’t) equal or identical, which can help prevent errors caused by accidentally comparing different data types or values. For example:
if x is y:
# do something here if x and y are the same object in memory
12. Use the “del” statement to delete a variable or object from memory, which can help prevent errors caused by accidentally using outdated data or resources. For example:
x = 5
y = x * 2
print(y)
del x
13. Avoid using dead batteries in your code. These are modules that have been deprecated and will be removed from the standard library in future versions of Python. Instead, look for alternatives or rewrite your code to use more modern libraries. For example:
if you’re currently using imghdr, then you can rewrite your code to use python-magic instead. Here, you’re identifying the type of a file:
Both the old, deprecated imghdr and the third-party python-magic library recognize that python-311.jpg represents a JPEG image file.
Check the documentation for details on how to install it on your operating system.
You can find a list of all the deprecated modules in the dead batteries PEP.
14. Use Python 3.11 whenever possible, as this version includes several new features and improvements like:
– Better error messages with more informative tracebacks
– Faster code execution due to considerable effort in the Faster CPython project
– Task and exception groups that simplify working with asynchronous code
– Several new typing features that improve Python’s static typing support
– Native TOML support for working with configuration files
15. Test your code on Python 3.11 to make sure it’s future-ready, and look out for any speedup or other benefits of using the newer version.