Common Anti-Pattern in Python – D-Zone Web Dev

  • Home / Web Development / Common Anti-Pattern in…

Common Anti-Pattern in Python – D-Zone Web Dev

1. Not used with To open files

When you open a file without with Statement, you should remember to close the file by call close() Clearly when finished with action. Even with the clear closure of resources, there are likely to be exceptions before the resources are actually released. This can lead to inconsistencies, or file corruption. Open a file via with The context manager implements a protocol that releases resources when they are not implemented with Block

Wrong action:

new_file = open('some-file.txt', 'r')
# do something exciting
new_file.close()

Good practice:

with open('some-file.txt', 'r') as fd:
    data = fd.read()
  # do something exciting

2. to use list/dict/set Unnecessarily compromised

Such as built-in functions all, any, enumerate, iter, itertools.cycle And itertools.accumulate A generator can work directly with expressions. They do not need to understand.

except these , all() And any() Python also supports short-circuiting, but this behavior is eliminated if this understanding is used. This affects performance.

Wrong action:

...
comma_seperated_names=",".join([name for name in my_fav_superheroes])

Good practice:

...
comma_seperated_numbers=",".join(name for name in my_fav_superheroes)

3. Unnecessary use of generators

It is not necessary to use generator expression in a call list, dict Or set Because there is understanding for each of these types. Instead of using list/dict/set Around generator expressions, they can be written as their relative understanding.

Wrong action:

squares = dict((i,i**2) for i in range(1,10))

Good practice:

squares = {i: i**2 for i in range(1,10)}

4. Returning more than one object type in a function call

Having conflicting return types in a function complicates the code and makes it difficult to understand, giving rise to bugs that are difficult to resolve. If a function wants to return a given type (such as integer permanent, list, tuple) but can do something else, the caller of that function will always need to check the price type. It is recommended to return only one type of object from a function.

If there is a need to return something blank in case of a failure, it is recommended to raise an exception that can be clearly caught.

Wrong action:

def get_person_age(name):
    person = db.get_person(name)
    if person:
        return person.age  # returns an int

    # returns None if person not found

Good practice:

def get_person_age(name):
    person = db.get_person(name)
    if not person:
        raise Exception(f'No person found with name {name}')
    return person.age  # guaranteed to return int every time

5. Not used get() Returning default values ​​from a dictionary

This affects the readability of the counter sample code. To create a variable we often look at the code, assign it a default value, and then check the dictionary for a specific key. If the key is present, then the value of the key is assigned to the value of the variable. Although there is nothing wrong with it, it is functional and ineffective because it double queries in the dictionary, while it can be used easily. get() Method for dictionary.

Wrong action:

currency_map = {'usd': 'US Dollar'}

if 'inr' in currency_map:
  indian_currency_name = currency_map['inr']
else:
  indian_currency_name="undefined"

Good practice:

currency_map = {'usd': 'US Dollar'}
indian_currency_name = currency_map.get('inr', 'undefined')

6. Not used items() To confess in a dictionary

items A dictionary-containing method returns a repeatable with key value tapes, which can be opened in one for Loop This approach is idiomatic and, therefore, is suggested.

Wrong action:

for code in country_map:
    name = country_map[code]
    # do something with name

Good practice:

for code, name in country_map.items():
    # do something with name
    pass

7. Don’t use literal syntax to start blanks list/dict/tuple

Starting an empty dictionary by calling is relatively slow dict() Because the name rather than using empty words dict If it is recovering, it should be looked at globally. The same is true of the other two types. list() And tuple().

Wrong action:

my_evans = list()
# Add something to this empty list

Good practice:

my_evans = []
# Add something to this empty list

8. Forwarding the debugger in the production code

Most of us have done this at least once – when debugging the code, you might press your code when you find a bug but forgot to remove the debugger. This is critical and can affect code behavior. It is highly recommended that the code be audited to remove debugger requests prior to verification.

With Python Analyzer, you can detect all of these counter-samples in a codecode before they are even produced.

Congratulations coding!

.

Write a Comment

Your email address will not be published. Required fields are marked *

x