【发布时间】:2021-02-12 06:27:55
【问题描述】:
__repr__ 用于返回对象的字符串表示,但在 Python 中,函数本身也是对象,can have attributes。
如何设置函数的__repr__?
我看到here 可以为函数外的函数设置属性,但通常在对象定义本身内设置__repr__,所以我想在函数定义本身内设置repr。
我的用例是我使用tenacity 重试具有指数退避的网络函数,并且我想记录我上次调用的函数的(信息性)名称。
retry_mysql_exception_types = (InterfaceError, OperationalError, TimeoutError, ConnectionResetError)
def return_last_retry_outcome(retry_state):
"""return the result of the last call attempt"""
return retry_state.outcome.result()
def my_before_sleep(retry_state):
print("Retrying {}: attempt {} ended with: {}\n".format(retry_state.fn, retry_state.attempt_number, retry_state.outcome))
@tenacity.retry(wait=tenacity.wait_random_exponential(multiplier=1, max=1200),
stop=tenacity.stop_after_attempt(30),
retry=tenacity.retry_if_exception_type(retry_mysql_exception_types),
retry_error_callback=return_last_retry_outcome,
before_sleep=my_before_sleep)
def connect_with_retries(my_database_config):
connection = mysql.connector.connect(**my_database_config)
return connection
目前retry_state.fn 显示类似于@chepner 所说的<function <lambda> at 0x1100f6ee0>,但我想向它添加更多信息。
【问题讨论】:
-
您可以使用 func.__name__ 打印函数的名称
-
我认为带有
__call__方法的类更适合这个用例。 -
@Georgy 似乎我在最初的搜索中错过了这一点,我的问题确实是一个重复的问题,但是这里的答案要好得多。