'Controlling screen output according to verbosity

I have a long web-scrapping Python project, and I like to control its screen output through a global variable called VERBOSITY. My functions are often defined like this.

GLOBAL1 = 'www.google.com'
VERBOSITY = 1

def search_something(url, word, verbosity=0):
    some_string = do_something()
    if verbosity:
        print(f'The word {word} generated {some_string}')
    return some_string

The problem is that now my code is full of indentations inside indentations and a lot of

if verbosity > 1:
   print('A lot of output, blabla')
elif verbosity > 0:
   print('A little output')

Is there any programming pattern or function often used to reduce this much repeating and indenting? I suppose I could invent a function like:

def print_threshold(msg, number):
   if number > 0:
      print(msg)

but I guess there is a well-stablished or method or convention.



Solution 1:[1]

You can use the mechanism of the logging module to achieve that. It has a system of log levels with which we can emulate the verbosity. This is a very simple example to demonstrate the idea:

import logging

VERBOSE = 1

if VERBOSE:
    level = logging.DEBUG
else:
    level = logging.INFO

logging.basicConfig(format="%(message)s", level=level)

logging.info("This is a regular message")
logging.debug("This is such a long message it should only be present when running with verbose")

Running this will print:

This is a regular message
This is such a long message it should only be present when running with verbose

While changing to VERBOSE = 0 will only output:

This is a regular message

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomerikoo