python shelve

pythonのshelveの使い方

タグ shelve permanent dbm


pythonのshelveの使い方

概要

  • dictの操作性のデータ構造を恒久化するpythonのデフォルトのライブラリ
  • dbmpickleで作られているらしい
  • open, closeのオペレーションが必要
    • つまり、マルチプロセスなどには対応しない

恒久化のタイミング

  • =で値を代入したとき

具体例

  • twitterのshort url(t.co)を展開するプログラムの例
import requests
import pandas as pd
import shelve

def reverse_tco(url):
    with shelve.open("dic") as dic:
        if dic.get(url) is None:
            r = requests.head(url)
            location = r.headers.get("Location")
            dic[url] = location # この時点で保存
        location = dic[url]
    return location

参考