Please enable Javascript to view the contents

开发 Tips(8)

 ·  ☕ 2 分钟

主要记录最近遇到的一些开发问题,解决方法。

1. Linux 下设置 Git 访问凭证

Windows 或 OS X 上有 keychain 工具管理账户凭证,在 Linux 系统上使用 Http/Https 协议访问 Git 仓库时,每次都需要输入账户密码。通过下面的配置,可以省略这一过程。

  1. 新建凭证文件
1
touch ~/.git-credentials
  1. 编辑文件,添加凭证信息
1
https://{username}:{password}@git-domain.com
  1. 使凭证生效
1
git config --global credential.helper store

执行完毕,会生成 Git 配置文件 ~/.gitconfig。

cat ~/.gitconfig
[user]
        email = yourmail
        name = yourname
[credential]
        helper = store

2. Python 列表、元组遍历速度差不多

在 IPython 中执行如下测试代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import timeit

a = range(9999)

def test_list():
    for i in a:
        i = i * i

timeit.timeit('test_list()', 'from __main__ import test_list', number=1000)
# 0.29664087295532227
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import timeit

a = tuple(range(9999))

def test_tuple():
    for i in a:
        i = i * i

timeit.timeit('test_tuple()', 'from __main__ import test_tuple', number=1000)
# 0.3050811290740967

从测试结果看到,list、tuple 的遍历速度差不多。但经常听到 tuple 比 list 快的言论,实际上指的是创建速度。另外,它们的查找速度也差不多。

在 CPython 中,创建 tuple 会一次性分配固定连续的内容;创建 list 会被分配两块内存,一块记录 Python Object 信息,一块用来存储数据。

3. Python 的类构造函数 type()

1
type(name, bases, dict)

参数说明:

  • name, 字符串,指定新类的名字, 赋给新类的 __name__
  • bases,一个 tuple,指定新类的基类,赋给新类的 __bases__
  • dict,字典类型,指定新类的属性,赋给新类的 __dict__

Python 作为一种动态语言,动态构建类能实现很多美妙特性、节省大量代码。

4. Python 中的 EAFP 原则

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the 07001 common to many other languages such as C.

举个例子:

EAFP 风格

1
2
3
4
try:
    x = my_dict["key"]
except KeyError:
    # handle missing key

LBYL 风格

1
2
3
4
if "key" in my_dict:
    x = my_dict["key"]
else:
    # handle missing key

LBYL 需要搜索字典两次,另外,可读性也没有 EAFP 好。

5. pipenv 应该与 pyenv 配合使用

pipenv 可以管理项目的依赖环境,隔离每一个项目。

1
pipenv shell

pipenv 还可以管理解释器,允许指定 Python 的版本。

1
2
pipenv --python 3.6
pipenv --python 2.7.14

执行上述命令时,pipenv 首先会在系统中寻找合适的版本。如果没有找到,同时安装了 pyenv,pipenv 会自动调用 pyenv 下载对应版本的 Python 解释器。

如果没有安装 pyenv,pipenv 仅会提示找不到匹配的版本。因此,在使用 pipenv 时,最好能配合 pyenv 使用。


微信公众号
作者
微信公众号