好代码系列(一):LazyObject
site-packages/django/utils/functional.py
def new_method_proxy(func):
def inner(self, *args):
if self_wrapped is empty:
self._setup()
return func(self._wrapped, *args)
return inner class LazyObject(object):
"""
A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the
instantiation. If you don't need to do that, use SimpleLazyObject.
""" # Avoid infinite recursion when tracing __init__ (#19456).
_wrapped = None def __init__(self):
self._wrapped = empty __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value):
if name == "_wrapped":
# Assign to __dict__ to avoid infinite __setattr__ loops.
self.__dict__["_wrapped"] = value
else:
if self._wrapped is empty:
self._setup()
setattr(self._wrapped, name, value) def __delattr__(self, name):
if name == "_wrapped":
raise TypeError("can't delete _wrapped.")
if self._wrapped is empty:
self._setup()
delattr(self._wrapped, name) def _setup(self):
"""
Must be implemented by subclasses to initialize the wrapped object.
"""
raise NotImplementedError('subclasses of LazyObject must provide a _setup() method') # Because we have messed with __class__ below, we confuse pickle as to what
# class we are pickling. We're going to have to initialize the wrapped
# object to successfully pickle it, so we might as well just pickle the
# wrapped object since they're supposed to act the same way.
#
# Unfortunately, if we try to simply act like the wrapped object, the ruse
# will break down when pickle gets our id(). Thus we end up with pickle
# thinking, in effect, that we are a distinct object from the wrapped
# object, but with the same __dict__. This can cause problems (see #25389).
#
# So instead, we define our own __reduce__ method and custom unpickler. We
# pickle the wrapped object as the unpickler's argument, so that pickle
# will pickle it normally, and then the unpickler simply returns its
# argument.
def __reduce__(self):
if self._wrapped is empty:
self._setup()
return (unpickle_lazyobject, (self._wrapped,)) # We have to explicitly override __getstate__ so that older versions of
# pickle don't try to pickle the __dict__ (which in the case of a
# SimpleLazyObject may contain a lambda). The value will end up being
# ignored by our __reduce__ and custom unpickler.
def __getstate__(self):
return {} def __deepcopy__(self, memo):
if self._wrapped is empty:
# We have to use type(self), not self.__class__, because the
# latter is proxied.
result = type(self)()
memo[id(self)] = result
return result
return copy.deepcopy(self._wrapped, memo)
好代码系列(一):LazyObject的更多相关文章
- iOS开发一行代码系列:一行搞定输入框
近期总结了下开发过程中经常使用的功能,发现有时候我在做反复性的劳动.于是决定把经常使用的功能抽出来,方便下次使用. 我的想法是:用最少的代码来解决这个问题.于是写了一些经常使用的工具类,名字就叫一行代 ...
- 自适应大邻域搜索代码系列之(1) - 使用ALNS代码框架求解TSP问题
前言 上次出了邻域搜索的各种概念科普,尤其是LNS和ALNS的具体过程更是描述得一清二楚.不知道你萌都懂了吗?小编相信大家早就get到啦.不过有个别不愿意透露姓名的热心网友表示上次没有代码,遂不过瘾啊 ...
- 二叉树(LeetCode) C++相关知识代码 系列1
0.二叉树最大深度 原题目:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes a ...
- 编写高质量的Python代码系列(八)之部署
Python提供了一些工具,使我们可以把软件部署到不同的环境中.它也提供了一些模块,令开发者可以把程序编写的更加健壮.本章讲解如何使用Python调试.优化并测试程序,以提升其质量与性能. 第五十四条 ...
- 编写高质量的Python代码系列(七)之协作开发
如果多个人要开发同一个Python程序,那就得仔细商量代码的写法了.即使你是一个人开发,也需要理解其他人所写的模块.本节讲解多人协作开发Python程序时所用的标准工具及最佳做法. 第四十九条:为每个 ...
- 编写高质量的Python代码系列(六)之内置模块
Python预装了许多写程序时会用到的重要模块.这些标准软件包与通常意义上的Python语言联系得非常精密,我们可以将其当成语言规范的一部分.本节将会讲解基本的内置模块. 第四十二条:用functoo ...
- 编写高质量的Python代码系列(四)之元类及属性
元类(metaclass)及动态属性(dynamic attribute)都是很强大的Python特性,然后他们也可能导致及其古怪.及其突然的行为.本节讲解这些机制的常见用法,以确保各位程序员写出来的 ...
- 编写高质量的Python代码系列(二)之函数
Python中的函数具备多种特性,这可以简化编程工作.Python函数的某些性质与其他编程语言中的函数相似,但也有性质是Python独有的.本节将介绍如何用函数来表达亿图.提升可复用程度,并减少Bug ...
- 少侠学代码系列(一)->JS起源
少侠:喂,有人吗?赶紧出来接客了,有没有人啊 帅气的我:来了来了,少侠有何吩咐? 少侠:把你们店里的秘籍呈上来我要学JS 帅气的我:少侠,别这样,我们秘籍是不外传的,祖上传下来的规矩,传人妖不传男女. ...
随机推荐
- UNITY自带的3D object没有三角形?
有方形,圆形,圆柱,胶囊,就是没有三角形? 这里看代码如何创建mesh http://www.narkii.com/club/thread-369573-1.html http://www.taikr ...
- C语言实现线程池
以前写过一篇关于如何使用多线程推升推送速度(http://www.cnblogs.com/bai-jimmy/p/5177433.html),能够到达5000qps,其实已经可以满足现在的业务,不过在 ...
- 配置Jenkins使用Gitlab的代码库进行构建
1. 首先确认Jenkins上安装了Git plugin, 以及Subversion plugin Manage Jenkins -> Plugin Manager -> Availabl ...
- SharePoint 2013常用开发工具分享
众所周知,一款好的开发工具不仅能提高项目开发效率,而且能够协助开发人员简化开发流程.本文汇总几款SharePoint 2013开发常用开发工具,希望能够对大家有所帮助.如果您有更好的工具,没有包含在本 ...
- 15-前端开发之JavaScript
什么是 JavaScript ? JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出 ...
- RAID级别
raid磁盘阵列,我们一般使用RAID 5,挂载单独硬盘测试读写速度,一般使用RAID0.
- js的this上下文的坑
很明显,this这个坑,在多层嵌套的时候还是一样被废,不管是call, apply还是bind. 例如: var fun = function() { this.name = 'test'; var ...
- 【OpenJudge 191】【POJ 1189】钉子和小球
http://noi.openjudge.cn/ch0405/191/ http://poj.org/problem?id=1189 一开始忘了\(2^{50}\)没超long long差点写高精度Q ...
- iOS小知识点(UI部分)
1. 父视图通过Tag来找到UIView UIView *targetView = [superView viewWithTag:10];//只在当前视图以及subviews中找,不能再孙子中找. 2 ...
- VOC2007检测任务的评估标准
VOC2007数据集使用mAP值作为检测算法检测结果的性能评估得分.mAP意思是mean Average Precision,Precision是指精度,Average Precision是指11个等 ...