19
2018-07-21 23:49:33 +08:00 1
这两天升级 django , 从 1.8 升级到 支持 python2.7 的最后一个版本 1.11.
发现
"Using user.is_authenticated() and user.is_anonymous() as a method "
"is deprecated. Remove the parentheses to use it as an attribute.",
之前的使用方法:user.is_authenticated()
现在的使用方法:user.is_authenticated
我看了一下 django 的实现方法
```
class User():
@property
def is_authenticated(self):
return CallableFalse
```
首先用 property 把它变成了一个属性,但是返回的不是一个 bool, 是一个有__call__ 的对象
CallableFalse = CallableBool(False)
```
class CallableBool:
"""
An boolean-like object that is also callable for backwards compatibility.
"""
do_not_call_in_templates = True
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
def __call__(self):
warnings.warn(
"Using user.is_authenticated() and user.is_anonymous() as a method "
"is deprecated. Remove the parentheses to use it as an attribute.",
RemovedInDjango20Warning, stacklevel=2
)
return self.value
def __nonzero__(self): # Python 2 compatibility
return self.value
def __repr__(self):
return 'CallableBool(%r)' % self.value
def __eq__(self, other):
return self.value == other
def __ne__(self, other):
return self.value != other
def __or__(self, other):
return bool(self.value or other)
def __hash__(self):
return hash(self.value)
```
你觉得这种实现方式 怎么样?
出了 这种需要兼容的代码, 再也没有见过 类似的代码了。