IPython源代码包括a getattr
check,用于测试'_ipython_canary_method_should_not_exist_'
函数开头是否存在get_real_method
:
def get_real_method(obj, name):
"""Like getattr, but with a few extra sanity checks:
- If obj is a class, ignore everything except class methods
- Check if obj is a proxy that claims to have all attributes
- Catch attribute access failing with any exception
- Check that the attribute is a callable object
Returns the method or None.
"""
try:
canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
except Exception:
return None
if canary is not None:
# It claimed to have an attribute it should never have
return None
尽管find其他编码员特别容易使用此名称,但是很容易找到有关原因的任何有意义的解释。
鉴于这两个类:
from __future__ import print_function
class Parrot(object):
def __getattr__(self, attr):
print(attr)
return lambda *a, **kw: print(attr, a, kw)
class DeadParrot(object):
def __getattr__(self, attr):
print(attr)
if attr == '_ipython_canary_method_should_not_exist_':
raise AttributeError(attr)
return lambda *a, **kw: print(attr, a, kw)
似乎IPython正在使用此方法的存在与否来决定是使用repr
还是使用rich display methods之一。故意阻止DeadParrot
中的测试会导致IPython查找并调用_repr_mimebundle_
。
我正在写一个假装所有attrs存在的对象。我如何决定是否特殊情况?