user3528438
user3528438

Reputation: 2817

How/when to close a file in an object?

I'm trying to design a class to manage video devices in Linux (/dev/video*).

Because of my C++ background I naturally thought I could open the file in the constructor and close it in the destructor.

Then later I learned python does not guarantee when/if the destructor is called.

Then I think I can make my own "initialize" and "de-initialize" methods to manage the opening/closing of the device file, but then it creates time gaps when the objected is constructed but not initialized and also when the object is de-initialized but not destructed, at which time the object does not have a valid internal state ( the methods are mostly ioctls on the opened video device).

That means I need to validate object state at the beginning of each method , like built-in file objects (f=open(), f.close)? Or just let the I/O error occur when a method is called on an already de-initialized object?

Upvotes: 2

Views: 1575

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308520

Go ahead and open the file in the constructor, it won't hurt anything.

Python provides the with statement to allow setup and teardown of an object beyond construction/destruction. Your object must include an __enter__ and __exit__ method; __enter__ is called at the beginning of the with statement, and __exit__ is called at the conclusion of the code block contained within the with. Notably __exit__ is called whether the block runs to completion or is terminated early with an exception.

Obviously with is only useful if you're using the object right then and there, not if you're storing it as a member in yet another object for example. But you can just go one level deeper and use with around that object, and have its __exit__ function call a cleanup function on your own object.

Upvotes: 1

Related Questions