Is there a better way to make a function silent on need? I got a piece of code I'm not pleased with; Does anyone would have a better idea?

def myFunc(verbose=True):
    if not verbose:
        print = functools.partial(globals()['print'], file=open(os.devnull, 'w'))
    else:
        # Required, othewise I got the error 'local print variable was referenced before being declared' a few lines below…
        print = globals()['print']

    # Bunch of code with tons of print calls […]


I also tried the classical sys.stdout = open(os.devnull, 'w') but it can't work with my code because my print function is defined as such at the beginning of the code:

print = functools.partial(print, file=codecs.getwriter('utf8')(sys.stdout.buffer)) # Make sure the output is in utf-8


But I'm not really fan about having to use globals twice.
It depends on what you are looking to do.  For localized 'quiet' code, I use this:

class NoStdStreams(object):
    def __init__(self,stdout = None, stderr = None):
        self.devnull = open(os.devnull,'w')
        self._stdout = stdout or self.devnull or sys.stdout
        self._stderr = stderr or self.devnull or sys.stderr

    def __enter__(self):
        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        self.old_stdout.flush(); self.old_stderr.flush()
        sys.stdout, sys.stderr = self._stdout, self._stderr

    def __exit__(self, exc_type, exc_value, traceback):
        self._stdout.flush(); self._stderr.flush()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr
        self.devnull.close()


then it is as easy as:

with NoStdStreams():
   print('you will never see this')


You could easily adapt it to:

with NoStdStreams(verbose):
    print('you may see this')