竞争无处不在,青春永不言败!专业撸代码,副业修bug

Talk is cheap , show me the code!



python 3.8 新特性

董伟明技术博客

安装 python 3.8 环境 , 在此刻 似乎 anaconda 都还不支持 3.8 ,所以直接下载源码进行编译安装

环境:  centos7.5

版本:python3.8

 

1、依赖包安装

yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel



2、下载包:

https://www.python.org/ftp/python/3.8.0/

wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0a1.tgz


3、解压:
tar -zxvf Python-3.8.0.tgz


4、安装:

cd Python-3.8.0
./configure --prefix=/usr/local/python3
make && make install

5、建立软连接

ln -s /usr/local/python3/bin/python3.8 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.8 /usr/bin/pip3

6、测试一下python3是否可以用

python3
pip3

赋值表达式

# 一个用法在 列表推导式
f = lambda x:x*2
[y for i in range(10) if(y:=f(i))]

# 另一个在 循环中间变量赋值

>>> with open('py38_test.txt','r') as fr:
...     while (line:=fr.readline()) != 'efg':
...         print(line)
... 
abc

位置参数


f-string 用来 字符串调试输出

>>> x=2
>>> print(f'{x**3}')

审计钩子

PEP 578: Python Runtime Audit Hooks
现在可以给 Python 运行时添加审计钩子:

In : import sys
...: import urllib.request
...:
...:
...: def audit_hook(event, args):
...: if event in ['urllib.Request']:
...: print(f'Network {event=} {args=}')
...:
...: sys.addaudithook(audit_hook)

In : urllib.request.urlopen('https://httpbin.org/get?a=1')
Network event='urllib.Request' args=('https://httpbin.org/get?a=1', None, {}, 'GET')
Out: <http.client.HTTPResponse at 0x10e394310>
目前支持审计的事件名字和 API 可以看 PEP 文档 (延伸阅读链接 2), urllib.Request 是其中之一。另外还可以自定义事件:

In : def audit_hook(event, args):
...: if event in ['make_request']:
...: print(f'Network {event=} {args=}')
...:

In : sys.addaudithook(audit_hook)

In : sys.audit('make_request', 'https://baidu.com')
Network event='make_request' args=('https://baidu.com',)

In : sys.audit('make_request', 'https://douban.com')
Network event='make_request' args=('https://douban.com',)
Multiprocessing shared memory

进程间共享内存

在Python 3.8中,multiprocessing模块提供了SharedMemory类,可以在不同的Python进城之间创建共享的内存区域。

typing 增强

Python是动态类型语言,但可以通过typing模块添加类型提示,以便第三方 工具 验证Python代码。Python 3.8给typing添加了一些新元素,因此它能够支持更健壮的检查:

改写的 fib 数列

# 原始的 fib 数列

(lambda f: f(f, int(input('Input: ')), 1, 0, 1))(lambda f, t, i, a, b: print(f'fib({i}) = {b}') or t == i or f(f, t, i + 1, b, a + b))

continue 可以出现在 finally 里了

while randint(0,1):
    try:
        1/0
    except:
        print('divided...error')
    finally:
        print('finally...')
        continue

posted @ 2019-10-16 13:31  云雾散人  阅读(2656)  评论(0编辑  收藏  举报

Your attitude not your aptitude will determine your altitude!

如果有来生,一个人去远行,看不同的风景,感受生命的活力!