How to write python code more elegantly

  • 2021-07-06 11:21:25
  • OfStack

Preface

Python the language of one of the greatest advantages is syntax concise, good code like pseudo-code 1, clean, neat, 1 clear. But sometimes we write code, especially Python beginners, often according to the thinking habits of other languages, which is not only slow to run, but also laborious to read the code, giving people a sloppy feeling, and even can't read it after a while.

Hal Aberson, author of the Construction and Interpretation of Computer Programs, once said: "Programs must be written for people to read, and only incidentally for machines to execute."

To write Pythonic (elegant, authentic and neat) code, you should also observe those Daniel codes at ordinary times. There are many excellent source codes worth reading on Github, such as requests, flask and tornado. The author lists some common writing methods of Pythonic, hoping to bring you 1 enlightenment.

1. Variable exchange

When exchanging the values of two variables in most programming languages, one temporary variable has to be introduced:


>>> a = 1
>>> b = 2
>>> tmp = a
>>> a = b
>>> b = tmp

pythonic


>>> a, b = b, a

2. Loop through interval elements


for i in [0, 1, 2, 3, 4, 5]:
(print i)
#  Or 
for i in range(6):
(print i)

pythonic


for i in xrange(6):
(print i)

xrange returns the generator object, which saves more memory than the list. However, it should be noted that xrange is written in python2, and python3 only has range method, which has the same characteristics as xrange.

3. Set traversal with index position

If you need to use the index position of the collection when traversing the collection, there is no index information when iterating directly on the collection, and the common way is to use it:


colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
print (i, '--->', colors[i])

pythonic


for i, color in enumerate(colors):
print (i, '--->', color)

4. String concatenation

When concatenating strings, the common way is to use + operation


names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
s = names[0]
for name in names[1:]:
s += ', ' + name
print (s)

pythonic


print (', '.join(names))

join is a more efficient string connection method. When + operation is used, every time + operation is executed, a new string object will be generated in memory, and 8 strings will be generated after 8 traversals, resulting in unnecessary memory waste. However, with join method, the whole process will only produce 1 string object.

5. Open/Close Files

When executing file operation, the last operation that must not be forgotten is to close the file, even if an error is reported, close is required. The common way is to call the close method shown in the finnally block.


f = open('data.txt')
try:
data = f.read()
finally:
f.close()

pythonic


with open('data.txt') as f:
data = f.read()

With the with statement, the system automatically closes the file object after the file operation is completed.

6. List derivation

Never use two lines of code when you can solve a problem concisely with one line of code, such as


>>> a, b = b, a
0

pythonic


>>> a, b = b, a
1

Similar to the generator expression, dictionary derivation, are very pythonic writing.

7. Make good use of decorators

The decorator can pull out the code that has nothing to do with business logic, keep the code clean and fresh, and the decorator can be reused in many places. For example, a function of crawling web pages, if the URL has been crawled, it will be directly obtained from the cache, otherwise it will be added to the cache after crawling down to prevent subsequent repeated crawling.


>>> a, b = b, a
2

pythonic


import urllib #py2
#import urllib.request as urllib # py3
def cache(func):
saved = {}
def wrapper(url):
if url in saved:
return saved[url]
else:
page = func(url)
saved[url] = page
return page
return wrapper
@cache
def web_lookup(url):
return urllib.urlopen(url).read()

Writing code with a decorator may seem like a lot more code on the surface, but it takes the cache-related logic out of the way and gives more function calls, so the total code is much less and the business method looks succinct.

8. Fair Use List
The list object (list) is a data structure that is more efficient for queries than for updates, such as deleting an element and inserting an element, which is very inefficient because the remaining elements have to be moved


>>> a, b = b, a
4

pythonic


>>> a, b = b, a
5

deque is a bi-directional queue data structure that deletes and inserts elements quickly

9. Sequence unpacking


>>> a, b = b, a
6

pythonic


>>> a, b = b, a
7

10. key and value of traversing dictionaries

Method 1 is not so fast, because hash has to be redone every iteration to find value corresponding to key.

Method 2 When the dictionary is very large, the memory consumption will be more than doubled


#  Method 1
for k in d:
print (k, '--->', d[k])
#  Method 2
for k, v in d.items():
print (k, '--->', v)

pythonic


>>> a, b = b, a
9

iteritems returns an iterator object, which saves more memory, but there is no such method in python3, only the items method, which is equivalent to iteritems.

Of course, there are many ways to write pythonic, which will not be listed in 11 here.


Related articles: