问题描述:

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?

网友答案:

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.

网友答案:
py_loglevel = getattr(logging, self.loglevel)
网友答案:

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"
相关阅读:
Top