Python:10 Quick Clean Coding Hacks

Python:10 Quick Clean Coding Hacks

it offers multiple ways to do the same task. It is also a very intuitive and easy language to read and write. That said, it is easy to get carried away with Python and make things appear more complex than they need to be. PEP8, the python style guide provides some guidelines to stay clean on python. Here is a quick list of 10 that you can immediately start doing in your code.

1. Do your co-developer a favor and use docstrings

Use “““Triple double quotes””” to write docstrings that clearly explain the purpose of your function, module and the script in all, even if you are commenting it otherwise. Remember to end your docstrings with a period. (.)

def get_percent_sales(product,sales,region):“““Return the product Sales volumes in percent of total in country.Get percentage of product sales of the region.This function gets the product and corresponding sales by region and returns a percent sales of the region by total sales in that country. Region input is accepted only by city. Districts are not accepted. If city name is not found, exception is thrown.         Parameters:              product (str) : Product name             sales (int) : Sales Volume         Returns: 
             percent_sales (float): Percent of total sales of    
                                    product.
"""

2. Make your logic statements intuitive to read

Don't

if is_white == Falseif not is_white == False

Do

is_white = Trueif is_white:else: 

3. Use .join instead of + to perform string concatenation

Don't

my_name = ‘firstname’+ ‘ ‘ + ‘lastname’

Do

my_name = " ".join(['firstname','lastname'])

4. Use List Comprehension for readable for loops

numbers = [1,2,3,4,5,6,7,8,9,10]

Don’t

even_halves = [ ]for num in numbers:
    if num%2 == 0:
       even_halves.append(num/2)print(even_halves)

Do:

even_halves = [num/2 for num in numbers if num%2==0]

5. If you are assigning a value to a variable, use def functions instead of lambda

Save the lambda functions for calculation inside of expressions.

Don’t

squared = lamdba x: x**2

Do

def squared(x):
   return x**2

6. Break those long lines

Pay attention to the text wrap line. Stay Inside your wrap line on the editor.

Don’t

df = pd.read_excel('This/extremely/long/file/path/that/extends/ /to/the/next/line/and/screws/with/indentation.xlsx')mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20000,30000,3100000320000]

do backslash and implicit continuation:

filepath = "this/sweet/line/" 
           "continued/prettily/"
           "looksbetter.xlsx"df = pd.read_excel(filepath)my_list = [1,2,3,4,5,6,7,8,9,10,11,
          12,13,14,15,16,17,18,19,
          20000,30000,3100000,320000]if this_happens or that_happens 
   or these_happen:
      print('blah')
else:
   print('the other blah')

 

Image for post

7. Use range instead of a list where possible

Don’t

indices = [0,2,4,6,8,10]for idX in indices:    print(name[idX])

do

for idX in range(0,12,2):    print(name[idX])

8. Keep a minimum amount of code under Try blocks

Don’t

try:   names = get_data(students, classroom)   numbers = get_scores(students, classroom)   return names,numbersexcept KeyError: 

Do:

try:    names = get_data(students, classroom)    numbers = get_scores(students, classroom)except KeyError:
    print('That's not a student in this classroom!')return names, numbers

9. Use sets a little more than you already do

Sets offer performance over functionality. If you don’t need a lot of functionality in the current situation, prefer sets to other data structures.

data = {‘find_this’, ‘among’, ‘all_the’,'other',’data’}if‘find_this’ in data:   print(‘this exists!’)long_stuff = [‘this’,’list’,’list’,’is’,
             ’enormous’,’oh’,’my’,’god’,
             ’god’,’what’,’is’,
             ’unique’,’unique’]unique_values = set(long_stuff) 

 

Image for post

10. use zip to iterate over multiple lists

students = [‘tom’,’dick’,’harry’,’larry’,’tim’,’benny’]scores = [100,20,40,60,30,40]

Don’t:

for i in range(len(students)):    print(student[i],scores[i]

Do

for student,score in zip(students,scores):
    print(student,score)

Also Read:

WhatsApp UPI based Payment Feature : Available for Indian Users

Post Comments(0)

Leave a reply