[Python-Dev] Using logging in the stdlib and its unit tests

Robert Kern robert.kern at gmail.com
Mon Dec 13 05:13:12 CET 2010

On 2010-12-12 21:30 , Nick Coghlan wrote:
> On Mon, Dec 13, 2010 at 11:22 AM, Robert Kern<robert.kern at gmail.com>  wrote:
>> level = getattr(logging, opt.logLevel)
> While this is the approach I would recommend, it does have a couple of
> downsides:
> 1. An upper() call is also needed to allow strings like "info" instead
> of "INFO":
> 2. If an integer is available, it would be nice to return it
> unmodified (or, if we ever get named values in the standard library,
> convert it to that)
> 3. The asymmetry with "logging.getLevelName" grates a bit
> So it would be far more obvious if there was a "logging.getLevel"
> counterpart to "logging.getLevelName" that looked something like:
> def getLevel(level):
>    try:
>      return operator.index(level) # Integers and equivalents
>    except TypeError:
>      pass
>    try:
>      key = level.upper()
>    except Exception as ex:
>      raise TypeError("Log level must be an integer or string") from ex
>    return globals()[key]

I don't think that the implementation should use globals(). I wouldn't want 
logging.getLevel('basic_format') to work. Instead, it should look it up in the 
known set of levels.

>> level = logging._levelNames[opt.logLevel]
> That doesn't work (_levelNames maps from integers to strings, we want
> the mapping from strings to integers and it is only the module globals
> that provides that).

At least in Python 2.6, it maps both ways. But then again, it is an 
_implementation _detail that should not be relied upon in your programs. I would 
suggest that there should be two dictionaries as part of the documented API, one 
mapping numbers to names and one mapping names to numbers. Or functions/methods 
returning said dictionaries. Having the entire mappings at hand is more useful 
than having functions that do the translation. They would allow you to 
auto-generate UIs (e.g. the help text for a --log-level argument or a radio box 
widget in a GUI). Having separate mappings makes them easier to work with than 
the 2.6-style _levelNames mapping.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-Dev mailing list