Why is dbf-table still open, if using "with tbl.open()"?

Question:

I use Ethan Furmans dbf-python-module (v. 0.99.3). If I use this code:

import dbf
tbl = dbf.Table(os.path.join(db_pfad, tabelle + ".dbf"))
with tbl.open(mode=dbf.READ_ONLY) as tbl:
    for rec in tbl:
          ...
tbl.close()

… everything is running fine.
But for my understanding of using with-clause, the last line tbl.close() should be redundant and superfluous. Leaving the range of with should close the table – not?
Anyway: If I ommit that line, the table will be left open!


Is this a bug in dbf-module or something I didn’t get right about with-clause in python?

Asked By: Orang Mutan

||

Answers:

When the with block is entered, the table is checked to see if it was already open, and if so leaves it open on exit — and you are manually opening it with the .open() call.

What you want to do is:

tbl = ...
with tbl:
    # do stuff

That will open the table in read/write mode, and close it when done. If you need it to be opened read-only, then there’s no point in using with:

tbl = ...
tbl.open(dbf.READ_ONLY)
for rec in tbl:
    ...
table.close()
Answered By: Ethan Furman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.