Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8816065
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T04:31:48+00:00 2026-06-14T04:31:48+00:00

I have a class that holds a strong reference to an open file. If

  • 0

I have a class that holds a strong reference to an open file. If the code runs without any exceptions then the file is closed correctly, because I explicitly call a method on the class that closes the file. However, if an exception is thrown then, the file is not closed correctly.

Here is a mocked up version of my code:

class MyFile(object):
    def __init__(self, filename, mode):
        self._handle = open(filename, mode)

    @classmethod
    def open(cls, filename, mode):
        return MyFile(filename, mode)

    def close(self):
        self._handle.close()

    def __del__(self):
        self.close()

    def writerow(data):
        # Special write
        pass

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.close()

Now if I were using this class at the top level of my code I would use a with statement:

def get_some_dat():
    return 1

with MyFile.open('foo.txt', 'w') as f:
    # do stuff with f
    data = get_some_data()
    f.writerow(data)

However, MyFile is opened indirectly by another object. I know that most Pythonistas will say that I should explicitly close the file, but I would like to make sure that the file is closed when the object is destroyed. The code that I’ve written will do the trick, but I was wondering if anyone had suggestions on a better way of implementing this behavior.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T04:31:49+00:00Added an answer on June 14, 2026 at 4:31 am

    Here is an example using weakref to ensure that the file is closed, even if it is opened without using the with ... syntax:

    import weakref
    
    class FileHandler:
        def __init__(self, dbf, caller = None):
            if caller is not None:
                self._ref = weakref.ref(caller, self.close)
            self.thefile = open(dbf, 'rb')
        def __enter__(self):
            return self
        def __exit__(self, ext_type, exc_value, traceback):
            self.close()
        def close(self, *args):
            print('closing file')
            self.thefile.close()
    
    class Foo:
        def __init__(self):
            self.fh = FileHandler('/tmp/testfile', caller = self)
    
    def autoclosing_file():
        foo = Foo()
    
    def demo_callback():
        with open('/tmp/testfile', 'w'): pass
        autoclosing_file()
    
    
    if __name__ == '__main__':
        demo_callback()
    

    prints

    closing file
    

    PS: I suspect that this code is not mine, but I’ve lost any reference to where it comes from. If someone knows, please tell so I can give proper attribution.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class that holds a few vectors, I'm not sure which method
I have a class that holds another objects inside it (List, Set and objects
I have a class Team that holds a generic list: [DataContract(Name = TeamDTO, IsReference
I have a QGraphicsObject derived class that holds a QImage and ovveride paint(QPainter *painter,
I have a private class variable that holds a collection of order items: Private
I have a class includes.vb that holds some variables (sharing them with other pages)
I have an abstract base class that holds a Dictionary. I'd like inherited classes
I have a class in C++ that I can't modify. However, that class holds
I have this small class called City that simply holds some information about a
I have a static std::map<std::string, CreateGUIFunc> in a class that basically holds strings identifying

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.