Effective Python
How to modify your Python code style, and use it in a more effective way, this post will introduce the pythonic code style to you.
####Language sugar and suggested code style
-
slice
You may see [::-1] in python, you also may see [begin:end], which is a brief edition of [begin:end:step]. [begin:end] is suggested, and [begin:end:step] often causes unexpected bugs, for example, it will break for Unicode characters -
str.format()
In C++ ect., %s is used to express a string, it works for python, but the suggested way to express string in python is:
- join
- with
To close a file immediately, use ‘with’ to operate the file.
- zip The zip() built-in function can be used to iterate over multiple iterators in parallel. And in Python 2, zip returns the full result as a list of tuples.
-
assert
use assert expression1,expression2 to capture the constraint defined by the user. -
deepcopy
Distinguish shallow copy from deep copy and ‘=’
- map & filter
usemap( func, seq1[, seq2...] )
to call a function and return a list of the results, which is equal to[f(x) for x in iterable]
.
- List comprehensions
When programming, frequently we want to transform one type of data into another. With the help of list comprehensions we can do it more effectively.
-
Concurrency & Parallelism
To make full use of the CPU resource of computer. Concurrent(Thread) program may run thousands of separate paths of execution simultaneously. In contrast, the time parallelism(Process) takes to do the total work is cut in half.
In python, The existence of GIL(Global Interpreter Lock) means your program could utilize only one thread at the same time.
I/O-bound:UseThreading
(false parallelism) for blocking I/O, which may take more time to execute the CPU-bound program. Also useLock
class in theThreading
to avoid data races which may not be avoid by GIL. CPU-bound:UseMultiprocessing
-
*args and **kwargs
Indef(arg, *args, **kwargs)
,*args
means all the default value of arguments, and**kwargs
means all the default key-value arguments. Inside of a function, we use args and kwargs(without *) to call the value passed to this function. -
docstring
Use docstring(Triple double-quoted strings) to describe your function and class.
- Generators
Generator is a kind of Iterator(which has next or __next__ def), However, during the iteration, the result of return will be created when they are called instead of storing them all in memory.
Reference
- Brett Slatkin Effective Python.
- Y.Zhang, Yh.Lai Writing Solid Python Code.