3

I am looking for a more elegant way to do the following:

py_loglevel = logging.DEBUG
if self.loglevel == "INFO":
   py_loglevel = logging.INFO
elif self.loglevel == "WARNING":
   py_loglevel = logging.WARNING
elif self.loglevel == "ERROR":
   py_loglevel = logging.ERROR

This works of couse, but it somehow annoys me because it is cluttering my code and is attracting my attention even though it is really trivial. Can this be done in a oneliner?

RickyA
  • 15,465
  • 5
  • 71
  • 95

3 Answers3

9

Use a dictionary:

levels = {
    'INFO': logging.INFO, 
    'WARNING': logging.WARNING,
    'ERROR': logging.ERROR,
}
py_loglevel = levels.get(self.loglevel, logging.DEBUG)

Alternatively, look up the name as an attribute on the module:

py_loglevel = getattr(logging, self.loglevel, logging.DEBUG)

provided the names match those defined on the module.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5
py_loglevel = getattr(logging, self.loglevel)
User
  • 14,131
  • 2
  • 40
  • 59
1

see this, a bad way is:

py_loglevel = logging.DEBUG
py_loglevel = (logging.INFO if self.loglevel == "INFO" else(logging.WARNING self.loglevel == "WARNING") else logging.ERROR)
print ":D"
Community
  • 1
  • 1
Vahid Kharazi
  • 5,723
  • 17
  • 60
  • 103