使用装饰器调试代码 [Python]

Debugging the code using decorator [Python]

我正在 python 中编写一些代码来尝试创建一个简单的面向套接字对象的服务器-客户端连接。我想保持我的代码干净,因此我宁愿排除过多的“if”语句。所以我的 class 服务器套接字定义如下所示:

class Server(object):

    def __init__(server_ip=LOCALHOST, server_port=55555, debug=True):

        # other code
        pass

所以如果有某种段落,当进行某种调试看起来很有用时,我已经包含了如下的 if 语句:

if debug:
    print("Something that helps the code debugging")

因此我想知道是否有办法从主 class 中排除这种类型的代码块并将它们添加到定义装饰器的包装函数中。那可能吗?如果可以,我该如何实现此功能?

非常感谢您的宝贵时间,另外,请原谅我的英语,我还在练习!

这取决于你,但实际上对于日志逻辑,使用 built-in 日志模块非常方便,它有一个清晰的设置模式:

import logging

logger = logging.getLogger(__name__)
log_handler = logging.streamHandler() # to output logs into stderr by default
logger.addHandler(log_handler)

logger.setLevel(logging.DEBUG) # here you set log level, you need to parametrize it (or dive deeper into logging docs)

def your_foo():
  logger.debug('Debug log message') # will only fire if log level == DEBUG

如果你仍然想坚持使用装饰器,我可以推荐这个演讲(关于装饰器的部分):James Powell: So you want to be a Python expert? | PyData Seattle 2017