Points Of Pythonic Code

  1. Return values from one place
  2. Alternatives to checking for equality
  3. Continuing a long line of code
    \ ()
  4. Unpacking
a, *rest = [1, 2, 3]
a, *middle, c = [1, 2, 3, 4]
a,__,c = [1, 2, 3] (use __ to replace name on position where its value will not need)
  1. Creating a length-N list of the same thing
image.png
  1. Whether element in an collection
image.png
  1. With statement
    __enter__() and __exit__()

  2. Testing your code
    (Testing Framwork)

  3. Logging

The setLevel()
method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there two setLevel()
methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on

  1. Choosing Licenses
image.png
  1. Context Manager
with EXPR as VAR:
    BLOCK

(1)执行EXPR语句,获取上下文管理器(Context Manager)

(2)调用上下文管理器中的enter方法,该方法执行一些预处理工作。

(3)这里的as VAR可以省略,如果不省略,则将enter方法的返回值赋值给VAR。

(4)执行代码块BLOCK,这里的VAR可以当做普通变量使用。

(5)最后调用上下文管理器中的的exit方法。

(6)exit方法有三个参数:exc_type, exc_val, exc_tb。如果代码块BLOCK发生异常并退出,那么分别对应异常的type、value 和 traceback。否则三个参数全为None。

(7)exit方法的返回值可以为True或者False。如果为True,那么表示异常被忽视,相当于进行了try-except操作;如果为False,则该异常会被重新raise。

  1. Spliting a long line into two shorter lines that make much better sense.
if badargs:
  err = 'create_cookie() got unexpected keyword arguments: {}'
  raise TypeError(err.format(sth))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容