jnwatson / py-lmdb

Universal Python binding for the LMDB 'Lightning' Database
http://lmdb.readthedocs.io/
Other
646 stars 106 forks source link

Use of 'with' context manager #325

Closed dineshbvadhia closed 2 years ago

dineshbvadhia commented 2 years ago

I want to understand the correct way to read/write/close with multiple databases. For example,

# open an env
env = open_env(data_folder, map_size, writemap=True)

# open db1
db1 = open_db(env, "db1".encode())

# open db2
db2 = open_db(env, "db2".encode())

# read from db2
with env.begin(db2, write=True) as txn:
    for i in range(1000):
        kv = txn.get(str(i).encode())

My assumption is: Once the env and the 2 databases are opened, the 2 databases can be read and written to. On exit from the 'with' context-manager, the env and the 2 databases are closed automatically so data can be flushed to disk.

But: Shouldn't the env (specifically) and the databases remain open until explicitly closed otherwise they are continuously being opened and closed for each set of transactions on the databases?

jnwatson commented 2 years ago

The exit from the context manager doesn't close the databases nor the environment. It merely ends/commits the transaction.

An explicit close of the environment or database is not necessary for data safety.