译Ditch these 7 bad habits in Python

Original title: Ditch These 7 Bad Habits in Python

Original link: jerryrnsh.com/ditch-these…

I have committed all these bad habits. It took me some time to change them.

Python is known for its simplicity and versatility. As one of the most commonly used programming languages, Python has many excellent tutorials. Unfortunately, this easy-to-learn syntax can sometimes mislead developers, especially those new to the language. Writing concise Python code can be tricky.

In this article, we’ll take a deep dive into some common mistakes and bad habits you might make when learning Python. It includes some things I wish someone had told me sooner.

Don’t worry, I won’t bore you with a bunch of words. Instead, I’ll provide you with easy-to-digest code snippets.

Brief description

  1. Use open and close instead of with
  2. Use empty list as default parameter
  3. Avoid list comprehensions
  4. Abuse of list generation
  5. Use Bare Except
  6. Wrong way to use == and is
  7. Use import *

1. Use open & amp; close instead of with statement

Working with file streams is probably the most common task when we start learning Python. Most tutorials will start by telling us to open and close a file using the following example:

f = open("stocks.txt", "r")
data = f.read()
f.close() # NOTE: Always remember to close!

In this case, we are often reminded to always close a file after using it because:

  • It consumes our limited system resources
  • It prevents us from moving or deleting files

Instead, the best practice is to always use context managers (with statements) in Python when handling file operations. Here is an example:

with open("stocks.txt", "r"):
    data = f.read()

Using a context manager here also helps us close the file in case of an exception.

Of course, we can also use the try-finally method. However, the with statement reduces our code to just two lines.

2. Use empty list or dictionary as default parameter

This is probably one of the most confusing questions for newbies to Python.

I have to admit, this question caught me off guard when I first started learning Python many years ago. I still remember that when I was first introduced to the wonders of default parameters, my use of functions was simply nonchalant. Below is an example:

def add_book(book_id, storage=[]):
    storage.append(book_id)
    return storage

my_book_list = add_book(1)
print(my_book_list)

my_other_book_list = add_book(2)
print(my_other_book_list)

# Expectation:
# [1]
# [2]

#Reality:
# [1]
# [1, 2] Huh, what? But they are different variables!

When you define a function, the default parameters (such as storage in the example above) are only created (i.e. evaluated) once.

Since lists in Python are mutable, the list will be modified each time the add_book() function is called. Here, the same list is used over and over again instead of creating a new list.

What you should do

# Do:
def add_book(book_id, storage=None):
    if storage is None:
        storage = []
        
    storage.append(book_id)
    return storage

The same concept applies to working with other mutable objects, such as dictionaries in Python.

3. Do not use list generation

List generation is undoubtedly one of the most unique features of Python. It undoubtedly helps improve code readability and is generally considered more elegant and “pythonic”.

Pythonic is an adjective that describes an approach to computer programming that is consistent with the founding philosophy of the Python programming language. There are many ways to accomplish the same task in Python, but there is usually a preferred method. This preferred way is called “pythonic”.

That being said, developers new to Python may have a hard time taking advantage of this feature, or at least getting used to it at first. Here is an example:

# Don't:
def generate_fruit_basket(fruits):
    """Without list comprehension"""
    basket = []
    for fruit in fruits:
        if fruit != "grapes":
            basket.append(fruit)

# Do:
def generate_fruit_basket_lc(fruits):
    """With list comprehension"""
    return [fruit for fruit in fruits if fruit != "grapes"]

The same logic applies to using dictionary expressions in Python.

4. Abuse of list generation

When we learned list generation. In pursuit of more “pythonic” code. You’ve seen too many examples of list generators being abused in various forms.

Even worse, some list comprehensions are written to such an extent that the code is no longer even readable, which defeats the purpose of using list comprehensions in the first place.

Here are some examples of what you shouldn’t do:

# Don't:
def get_book_price(inventory):
    return [(book, price) for book in inventory if book.startswith('A') for price in inventory[book] if price > 10]

# Perhaps slightly better...? But please don't.
def get_book_price(inventory):
    return [
        (book, price) for book in inventory
        if book.startswith('A')
        for price in inventory[book]
        if price > 10
    ]

Although list generation code is more compact and runs faster, we should avoid writing long and complex list comprehensions (especially single lines) to ensure the readability of the code. Don’t be bothered by list comprehensions.

5. Use Bare Except

When catching exceptions, whenever possible, mention the specific exception rather than using a simple except: clause.

Here is an example of Bare Except:

# Do NOT ever use bare exception:
while True:
    try:
        input_string = input("Input something")
        converted_input = int(input_string)
        print(converted_input)
    
    except: # Can't do Ctrl + C to exit!
        print("Not a number!")

In short, we shouldn’t use bare except because it will catch all exceptions, including some that we don’t want to catch, like KeyboardInterrupt in this case (we want to exit the application).

An empty except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it more difficult to interrupt the program with Control-C, and can be masked other problems. If you want to catch all exceptions that represent program errors, use the except Exception: statement (bare except is equivalent to except BaseException:).

Should not be used:

# Not use bare except
try:
    user = User.objects.get(pk=user_id)
    user.send_mail('Hello world')
except:
    logger.error('An error occurred!')

Best Practices:

# Use this
try:
    user = User.objects.get(pk=user_id)
    user.send_mail('Hello world')
except User.DoesNotExist:
    logger.error('The user does not exist with that ID')

Beyond that, it makes debugging a nightmare because it causes the application to fail without us knowing why. So please stop using exceptions like this.

6. Wrong way to use == and is

But does it really matter? I’ve seen it too much in Python code in the wild. If you didn’t know, they are different.

  • The is operator checks whether two items refer to the same object (i.e. exist in the same memory location). Also called reference equality.
  • The == operator checks whether values are equal.

Here’s a simple example to illustrate what I mean:

# NOTE: In Python everything is an object, including list
listA = [1, 2, 3]
listB = [1, 2, 3]

listA is listB # False because they are NOT the same actual object
listA == listB # True because they are equivalent

The following summarizes considerations for using the is and == operators:

# Do:
if foo is None:
    ...

#Don't:
if foo == None:
    ...

# Do:
if not bar:
    ...

#Don't:
if bar == False:
    ...

# Do:
if baz:
    ...

#Don't:
if baz is True:
    ...

#Don't
if baz == True:
    ...

7. Use import * (asterisk)

Many people will think this is for convenience. But this is just laziness.

Using import * has the potential to pollute the current namespace, since it will import all functions and classes in the library.

What does “Polluting the namespace” mean? In layman’s terms, the functions (or classes) you import using import * may conflict with the functions you define.

Basically, you run the risk of overwriting a variable or function and eventually it becomes difficult to tell which function comes from which variable or function.

Final Thoughts

Python is a relatively easy programming language to get started with. The many mechanisms and paradigms it comes with greatly improve our work efficiency as developers.

Still, it’s easy to fall into the habit of writing bad code in Python. Upon reflection, this article has also reminded me (and hopefully you too) to stay away from these bad Python coding habits.

There are so many things not to do in this article.

There are a few things you can do – start using tools like autopep8, flake8, pylint or even mypy to keep your code quality at the highest standard. They will help you check your code against standards like PEP8, making you a better developer.

I hope this article was helpful and happy coding!


———————————END——————- ——–

Digression

Thank you for watching until the end, I have prepared some benefits for everyone!

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.


CSDN gift package:The most complete “Python learning materials” on the entire network are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Essential development tools for Python

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

CSDN gift package:The most complete “Python learning materials” on the entire network are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.