Parse --verbose occurrences into a logging level
Also published in our Blogger archive.
Repeated verbosity flags are a compact command-line convention, but counting them is separate from choosing logging behavior. argparse supplies action="count" to count occurrences of an option. This article maps that integer with a small, explicit policy: no flags means WARNING, one means INFO, and two or more mean DEBUG.
The parser accepts both -v and --verbose. Its default=0 is important: without it, an omitted count option has the default value None. The example parses three synthetic argument lists: [], [-v], and [-vv]. argparse recognizes the grouped short form as two occurrences, then logging_level() converts the counts to standard logging constants. logging.getLevelName() makes the deterministic output readable: WARNING INFO DEBUG. The assertion verifies those three cases and the selected policy for them.
This is not a universal verbosity scale. In particular, the function intentionally treats three or more occurrences the same as two; a program wanting TRACE, third-party logging levels, or different production defaults must define that behavior itself. The code parses supplied lists rather than the process command line, which makes the example deterministic but does not demonstrate shell quoting, command dispatch, or logging handler configuration. Counting an option does not by itself emit, filter, or format any log messages.
argparse has been in the standard library since Python 3.2; the documented count action requires no newer API. AI assistance disclosure: this article was drafted with AI assistance.
See the official argparse documentation.
import argparse
import logging
def logging_level(occurrences):
if occurrences == 0:
return logging.WARNING
if occurrences == 1:
return logging.INFO
return logging.DEBUG
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-v", "--verbose", action="count", default=0)
levels = [
logging.getLevelName(logging_level(parser.parse_args(arguments).verbose))
for arguments in ([], ["-v"], ["-vv"])
]
assert levels == ["WARNING", "INFO", "DEBUG"]
print(" ".join(levels))
WARNING INFO DEBUG