IPython源代码包括一个getattr检查函数'_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
Run Code Online (Sandbox Code Playgroud)
虽然很容易找到其他编码器特别设置这个名称,但更难找到任何有意义的解释原因.
鉴于这两个类:
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)
Run Code Online (Sandbox Code Playgroud)
似乎IPython正在使用此方法的存在或缺乏来决定是使用repr还是使用其丰富的显示方法之一.故意阻止测试DeadParrot会导致IPython查找并调用_repr_mimebundle_.
我正在写一个假装所有attrs存在的对象.我如何决定是否特殊情况呢?
| 归档时间: |
|
| 查看次数: |
552 次 |
| 最近记录: |