karlicoss / orgparse

Python module for reading Emacs org-mode files
https://orgparse.readthedocs.org
BSD 2-Clause "Simplified" License
371 stars 43 forks source link

orgparse.load() generates a ResourceWarning when called with a text file #45

Closed niclasborlin closed 2 years ago

niclasborlin commented 2 years ago

Consider the attached files testorgparse.py and test.org.

The file testorgparse.py is a simple test of orgparse.load() on an external text file test.org using unittest. It contains the following:

import orgparse
import unittest
import os

class TestLoadOrgFile(unittest.TestCase):
    """A class for testing check_org_file"""

    def test_check_org_file_ok(self):
        file_dir = os.path.dirname(os.path.abspath(__file__))
        test_file = os.path.join(file_dir,"test.org")
        s = orgparse.load(test_file)

if __name__ == "__main__":
    # Run self-tests
    unittest.main()

The file test.org is a simple, one-line org file and should reside in the same directory as testorgparse.py. Then, the call below generates a ResourceWarning due to an unclosed file in loadparse.load():

$ python3 testorgparse.py 
testorgparse.py:11: ResourceWarning: unclosed file <_io.BufferedReader name='/home/user/python/test.org'>
  s = orgparse.load(test_file)
ResourceWarning: Enable tracemalloc to get the object allocation traceback
.
----------------------------------------------------------------------
Ran 1 test in 0.004s

OK

The pushed code fixes the warning by enclosing codecs.open() by a with statement.

This is the output with the modified code:

$ python3 testorgparse.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

test_load.zip

niclasborlin commented 2 years ago

Forgot to add:

$ python3 --version
Python 3.8.5
karlicoss commented 2 years ago

thanks, good catch! I guess in theory would be nice if it was iterative (presumably then loadi would have to be under with block as well). However seems that readline always converts to a list anyway, so this change is OK!