Home > database >  Use python eval() in method calls
Use python eval() in method calls

Time:03-26

I have used eval() before but I'm trying to use it in a method call and it's not working.

    if level == 'info':
            logging.info(
                f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
            )
        elif level == 'warning':
            logging.warning(
                f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
            )
        elif level == 'error':
            logging.error(
                f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
            )
        elif level == 'critical':
            logging.critical(
                f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
            )

How do I make less code by using something like:

    level == 'info':
    logging.eval(level)(
                f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
            )

I really thought this last one was gonna work:

    level = 'info'
    log = f"{logging}.{eval(level)}"
        eval(log)(f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}")

Anyone knows a way to make this work?

CodePudding user response:

Using eval is usually a bad idea. You could use getattr, e.g.:

getattr(logging, level)(
    f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
)

That way you aren't executing arbitrary code based on what level contains, just trying to get an attribute of that name from logging (and raising AttributeError immediately if it's not valid).

FWIW, I would implement this the other way around -- have this method return the logging string, and have the caller supply that to logging.whatever. The caller already needs to know which specific logging function it's calling; if you just have it call the actual function rather than passing its name as a string literal, it's easier to catch typos/etc via static analysis.

CodePudding user response:

Why not simply use the logging.log function from logging?

loggging.log(level, msg)

See logging

CodePudding user response:

You can do like this and its simple if i understand :-

error = {
    'info':logging.info,
    'warning':logging.warning,
    'error':logging.error,
    'critical':logging.critical,
}
massage = f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}"
error.get(level)(massage)
  • Related