代码之家  ›  专栏  ›  技术社区  ›  Michael Deardeuff

搁置模块有问题吗?

  •  2
  • Michael Deardeuff  · 技术社区  · 16 年前

    使用shelve模块给了我一些令人惊讶的行为。keys()、iter()和iteritem()不会返回工具架中的所有条目!代码如下:

    cache = shelve.open('my.cache')
    # ...
    cache[url] = (datetime.datetime.today(), value)
    

    稍后:

    cache = shelve.open('my.cache')
    urls = ['accounts_with_transactions.xml', 'targets.xml', 'profile.xml']
    try:
        print list(cache.keys()) # doesn't return all the keys!
        print [url for url in urls if cache.has_key(url)]
        print list(cache.keys())
    finally:
        cache.close()
    

    ['targets.xml']
    ['accounts_with_transactions.xml', 'targets.xml']
    ['targets.xml', 'accounts_with_transactions.xml']
    

    先验 ?

    2 回复  |  直到 16 年前
        1
  •  3
  •   SilentGhost    16 年前

    python library reference :

    …不幸的是,数据库也受到dbm的限制,如果使用它,这意味着存储在数据库中的对象(的酸洗表示)应该相当小。..

    这正确地再现了“bug”:

    import shelve
    
    a = 'trxns.xml'
    b = 'foobar.xml'
    c = 'profile.xml'
    
    urls = [a, b, c]
    cache = shelve.open('my.cache', 'c')
    
    try:
        cache[a] = a*1000
        cache[b] = b*10000
    finally:
        cache.close()
    
    
    cache = shelve.open('my.cache', 'c')
    
    try:
        print cache.keys()
        print [url for url in urls if cache.has_key(url)]
        print cache.keys()
    finally:
        cache.close()
    

    输出:

    []
    ['trxns.xml', 'foobar.xml']
    ['foobar.xml', 'trxns.xml']
    

    因此,答案是不要像原始xml那样存储任何大的东西,而是将计算结果存储在架子上。

        2
  •  0
  •   Aaron Digulla    16 年前

    看到你的例子,我的第一个想法是 cache.has_key()

    print cache.has_key('xxx')
    print list(cache.keys())