Home>

One of the biggest advantages of Python is its concise syntax.Good code is like pseudo code,Clean, tidy and clear.To write pythonic (elegant, authentic, neat) code, you need to read more and learn the code written by Daniels.There are a lot of excellent source code on github worth reading,For example:requests, flask, tornado, here are some common pythonic writing.

0. The program must be readable first,Only then can the computer execute it.

"Programs must be written for people to read, and only incidentally for machines to execute."

Exchange assignment

##Not recommended
temp=a
a=b
b=a
##recommend
a, b=b, a #First generate a tuple object, then unpack

Unpacking

##Not recommended
l=["david", "pythonista", "+ 1-514-555-1234"]
first_name=l [0]
last_name=l [1]
phone_number=l [2]
##recommend
l=["david", "pythonista", "+ 1-514-555-1234"]
first_name, last_name, phone_number=l
#python 3 only
first, * middle, last=another_list

3. Use the operator in

##Not recommended
if fruit == "apple" or fruit == "orange" or fruit == "berry":
  #Multiple judgments
##recommend
if fruit in ["apple", "orange", "berry"]:
  #Use in for more conciseness

4. String operations

##Not recommended
colors=["red", "blue", "green", "yellow"]
result=""
for s in colors:
  result +=s #discard the previous string object with each assignment, Generate a new object
##recommend
colors=["red", "blue", "green", "yellow"]
result="" .join (colors) #No additional memory allocation

5. List of dictionary keys

##Not recommended
for key in my_dict.keys ():
  #my_dict [key] ...
##recommend
for key in my_dict:
  #my_dict [key] ...
#Only when the key value needs to be changed in the loop,We need to use my_dict.keys ()
#Generate a static list of keys.

6. Dictionary key value judgment

##Not recommended
if my_dict.has_key (key):
  #... do something with d [key]
##recommend
if key in my_dict:
  #... do something with d [key]

7. Dictionary get and setdefault methods

##Not recommended
navs=()
for (portfolio, equity, position) in data:
  if portfolio not in navs:
      navs [portfolio]=0
  navs [portfolio] +=position * prices [equity]
##recommend
navs=()
for (portfolio, equity, position) in data:
  #Use the get method
  navs [portfolio]=navs.get (portfolio, 0) + position * prices [equity]
  #Or use setdefault method
  navs.setdefault (portfolio, 0)
  navs [portfolio] +=position * prices [equity]

8. Judging the authenticity

##Not recommended
if x == true:
  #....
if len (items)!=0:
  #...
if items!=[]:
  #...
##recommend
if x:
  #....
if items:
  #...

9. Traversing the list and index

##Not recommended
items="zero one two three" .split ()
#method 1
i=0
for item in items:
  print i, item
  i +=1
#method 2
for i in range (len (items)):
  print i, items [i]
##recommend
items="zero one two three" .split ()
for i, item in enumerate (items):
  print i, item

10. List comprehension

##Not recommended
new_list=[]
for item in a_list:
  if condition (item):
    new_list.append (fn (item))
##recommend
new_list=[fn (item) for item in a_list if condition (item)]

11. List comprehensions-nesting

##Not recommended
for sub_list in nested_list:
  if list_condition (sub_list):
    for item in sub_list:
      if item_condition (item):
        #do something ...
##recommend
gen=(item for sl in nested_list if list_condition (sl) \
      for item in sl if item_condition (item))
for item in gen:
  #do something ...

12. Loop nesting

##Not recommended
for x in x_list:
  for y in y_list:
    for z in z_list:
      #do something for x&y
##recommend
from itertools import product
for x, y, z in product (x_list, y_list, z_list):
  #do something for x, y, z

13. Try to use generators instead of lists

##Not recommended
def my_range (n):
  i=0
  result=[]
  while i<n:
    result.append (fn (i))
    i +=1
  return result #return to list
##recommend
def my_range (n):
  i=0
  result=[]
  while i<n:
    yield fn (i) #use generator instead of list
    i +=1
* Try to use generators instead of lists,Unless a list-specific function must be used.

14. Try to use imap/ifilter instead of map/filter for intermediate results

##Not recommended
reduce (rf, filter (ff, map (mf, a_list)))
##recommend
from itertools import ifilter, imap
reduce (rf, ifilter (ff, imap (mf, a_list)))
* lazy evaluation will bring higher memory usage efficiency,Especially when dealing with big data operations.

15. Use any/all function

##Not recommended
found=false
for item in a_list:
  if condition (item):
    found=true
    break
if found:
  #do something if found ...
##recommend
if any (condition (item) for item in a_list):
  #do something if found ...

16. Property

=
##Not recommended
class clock (object):
  def __init __ (self):
    self .__ hour=1
  def sethour (self, hour):
    if 25&gt;hour>0:self .__ hour=hour
    else:raise badhourexception
  def gethour (self):
    return self .__ hour
##recommend
class clock (object):
  def __init __ (self):
    self .__ hour=1
  def __sethour (self, hour):
    if 25&gt;hour>0:self .__ hour=hour
    else:raise badhourexception
  def __gethour (self):
    return self .__ hour
  hour=property (__ gethour, __sethour)

17. Open file with with

##Not recommended
f=open ("some_file.txt")
try:
  data=f.read ()
  #Other file operations.
.
finally:
  f.close ()
##recommend
with open ("some_file.txt") as f:
  data=f.read ()
  #Other file operations.
..

18. Use with to ignore exceptions (python 3 only)

##Not recommended
try:
  os.remove ("somefile.txt")
except oserror:
  pass
##recommend
from contextlib import ignored #python 3 only
with ignored (oserror):
  os.remove ("somefile.txt")

19. Use with to handle locks

##Not recommended
import threading
lock=threading.lock ()
lock.acquire ()
try:
  #Mutex operation.
..
finally:
  lock.release ()
##recommend
import threading
lock=threading.lock ()
with lock:
  #Mutex operation.
..

20. References

1) idiomatic python:

2) pep 8:style guide for python code:

to sum up

  • Previous Solve the problem of loading resources after vue-cli webpack is packaged
  • Next How Django customizes pagination