简体   繁体   中英

Typing for dynamically generated class methods

I wrote a tiny, compact, minimal logger for Python apps that are little more than slightly large scripts. It has colors (which are very important), and allows you to define a custom level (a custom log.<level_name> and color) by just adding a new tuple to the list of levels passed to the Logger constructor.

However, since the methods are defined on the resulting class instance dynamically, Pylint in VS Code can't find the methods when I invoke them.

Is there any way, eg with type hints, to tell Pylint/all static-analysis tools about these methods or at least have them not worry about them?

Here's the class's source:

class Logger:
    def __init__(self, levels):
        max_level_len = max(len(l) for l, _ in levels)
        for level, color in levels:
            l = level.rjust(max_level_len)
            func = eval(f"lambda msg: print('\x1b[1m{color}{l}:{color} ' + msg + '\x1b[0m')")
            setattr(self, level, func)

Usage:

log = Logger(
    [
        ("info", "\x1b[94m"),
        ("exec", "\x1b[96m"),
        ("warning", "\x1b[93m"),
        ("error", "\x1b[91m"),
        ("critical", "\x1b[91m"),
        ("fatal", "\x1b[91m"),
        ("success", "\x1b[92m"),
        ("debug", "\x1b[95m"),
    ]
)

log.info("Test")
log.critical("Test")

When you say "find the methods" - you mean the log.info methods?

Thats probably because your Logger class isn't inheriting from anything, so doesn't have those methods.

Probably a better approach than what you are trying is to define a formatter. Something like this-

colors = {
    'default': 'aaaa',
    logging.DEBUG: 'bbbb',
}

class ColoredFormatter(Formatter):
  def __init__():
    super().__init__(fmt="%(levelname)s <whatever else you want>")

  def formatMessage(record):
    record.msg = f"{colors[record.level]}record.msg{colors['default']}"
    super().formatMessage(record)


handler = StreamHandler()
handler.setFormatter(ColoredFormatter)
logging.basicConfig(handlers=[handler])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM