3

I have several functions that I want to set the verbosity level of. Currently, I'm handling it like so:

class Foo:
    def __init__(self, foo_stuff, verbose=True):
        self.print_file = None if verbose else open(os.devnull, 'w')

    def do_stuff(self):
        print('doing stuff', file=self.print_file)

This works, but I don't like that I never close the file self.print_file.

For cleanliness, I'd prefer not to wrap every single print function in a with open(...). I was wondering if anyone could suggest another way of doing this. For this application, I don't think the python logging module will work.

1 Answer 1

1

atexit module may help. write a cleanup function in your Foo class and register it by calling

atexit.register(function, args)

to be called before your program exits.

Sign up to request clarification or add additional context in comments.

2 Comments

Researching your suggestion lead me to the magic method __del__ (rszalski.github.io/magicmethods). Do you know if this approach works? ...it comes with a warning on this type of operation
Never used it. Checked the page you linked, it looks promising, I would definitely give it a shot :) But be sure that you read the warnings first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.