python2 nonlocal_python非零返回

python2 nonlocal_python非零返回nonlocal可以将一个变量声明为非本地变量,在python的lru_cache看到了使用defdecorator(func):a=1defwrapper(*args,**kwargs):nonlocalaa+=1returnfunc()returnwrapper实例中,当a变量是不可变类型时,因为包装函数引用了a,装饰器执行结束,在包装函数里改变a的值,需要…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

nonlocal 可以将一个变量声明为非本地变量, 在python的lru_cache看到了使用

def decorator(func):

a = 1

def wrapper(*args, **kwargs):

nonlocal a

a += 1

return func()

return wrapper

实例中, 当a变量是不可变类型时, 因为包装函数引用了a, 装饰器执行结束, 在包装函数里改变a的值, 需要用nonlocal声明a变量. (a是自由变量了)

当a是可变类型时, 可以不用声明nonlocal a

自己再本地试一遍能理解的更加深入

lru_cache源码中的使用, 用来记录hit和miss

只贴出包装函数的部分

f _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):

# Constants shared by all lru cache instances:

sentinel = object() # unique object used to signal cache misses

make_key = _make_key # build a key from the function arguments

PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields

cache = {}

hits = misses = 0

full = False

cache_get = cache.get

cache_len = cache.__len__

lock = RLock()

root = []

root[:] = [root, root, None, None]

if maxsize == 0:

def wrapper(*args, **kwds):

nonlocal misses # 要改变misses,所以用nonlocal声明

misses += 1

result = user_function(*args, **kwds)

return result

elif maxsize is None:

def wrapper(*args, **kwds):

# Simple caching without ordering or size limit

nonlocal hits, misses

key = make_key(args, kwds, typed)

result = cache_get(key, sentinel)

if result is not sentinel:

hits += 1

return result

misses += 1

result = user_function(*args, **kwds)

cache[key] = result

return result

else:

def wrapper(*args, **kwds):

# Size limited caching that tracks accesses by recency

nonlocal root, hits, misses, full

key = make_key(args, kwds, typed)

with lock:

link = cache_get(key)

if link is not None:

# Move the link to the front of the circular queue

link_prev, link_next, _key, result = link

link_prev[NEXT] = link_next

link_next[PREV] = link_prev

last = root[PREV]

last[NEXT] = root[PREV] = link

link[PREV] = last

link[NEXT] = root

hits += 1

return result

misses += 1

result = user_function(*args, **kwds)

with lock:

if key in cache:

# Getting here means that this same key was added to the

# cache while the lock was released. Since the link

# update is already done, we need only return the

# computed result and update the count of misses.

pass

elif full:

# Use the old root to store the new key and result.

oldroot = root

oldroot[KEY] = key

oldroot[RESULT] = result

# Empty the oldest link and make it the new root.

# Keep a reference to the old key and old result to

# prevent their ref counts from going to zero during the

# update. That will prevent potentially arbitrary object

# clean-up code (i.e. __del__) from running while we’re

# still adjusting the links.

root = oldroot[NEXT]

oldkey = root[KEY]

oldresult = root[RESULT]

root[KEY] = root[RESULT] = None

# Now update the cache dictionary.

del cache[oldkey]

# Save the potentially reentrant cache[key] assignment

# for last, after the root and links have been put in

# a consistent state.

cache[key] = oldroot

else:

# Put result in a new link at the front of the queue.

last = root[PREV]

link = [last, root, key, result]

last[NEXT] = root[PREV] = cache[key] = link

# Use the cache_len bound method instead of the len() function

# which could potentially be wrapped in an lru_cache itself.

full = (cache_len() >= maxsize)

return result

def cache_info():

“””Report cache statistics”””

with lock:

return _CacheInfo(hits, misses, maxsize, cache_len())

def cache_clear():

“””Clear the cache and cache statistics”””

nonlocal hits, misses, full

with lock:

cache.clear()

root[:] = [root, root, None, None]

hits = misses = 0

full = False

wrapper.cache_info = cache_info

wrapper.cache_clear = cache_clear

return wrapper

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/196825.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 5分钟入门Cinemachine智能相机系统

    5分钟入门Cinemachine智能相机系统摘要:相机是Unity世界的眼睛,一个智能相机更是能帮咱们节省大把的时间和精力。Cinemachine现在已经大量应用到各种项目中,如果你还没有用过Cinemachine,墙裂建议你来体验一下。你好,我是跟着大智学Unity的萌新,我叫小新,这是我本周的学习总结报告哦。Cinemachine入门Cinemachine入门还是很容易的,5分钟足矣,但是深入去研究里面也有很多门道。安装C…

    2022年5月28日
    45
  • 10个调试Java的技巧建议收藏

    调试不仅可以查找到应用程序缺陷所在,还可以解决缺陷。对于Java程序员来说,他们不仅要学会如何在Eclipse里面开发像样的程序,更需要学会如何调试程序。本文介绍了Java程序员必知的10个调试技巧,

    2021年12月20日
    46
  • qq视频资源是什么_qq代码视频教程

    qq视频资源是什么_qq代码视频教程QQ视频资源裂变源码有哪些功能对于2021年网赚引流最快变现的一些思路qq资源!已解锁全部!点击进入观赏!这个是分享以后得卡片标题内容这个系统有2个版本,第一调用单个视频资源链接(支持mp4,m3u8格式),第二个版本支持观看10-60秒后强制分享弹窗下上图片位置带自定义图片广告跳转,跳转链接可批量留多个裂变网页链接达到裂变式框架“`…

    2022年8月24日
    11
  • docker启动mysql并打开远程连接「建议收藏」

    docker启动mysql并打开远程连接「建议收藏」1.获取mysql:拉去mysql镜像dockerpullmysql:8.02.启动mysql#–name指定容器名字-v目录挂载-p指定端口映射-e设置mysql参数-d后台运行dockerrun–namemysql-v/usr/local/mysql/data:/var/lib/mysql-v/usr/local/mysql:/etc/mysql/conf.d-v/usr/local/mysql/log:/var/log/mysql-eMYSQL

    2022年9月1日
    3
  • Hibernate学习笔记:hibernate二级缓存攻略

    Hibernate学习笔记:hibernate二级缓存攻略
     hibernate的session提供了一级缓存,每个session,对同一个id进行两次load,不会发送两条sql给数据库,但是session关闭的时候,一级缓存就失效了。
    二级缓存是SessionFactory级别的全局缓存,它底下可以使用不同的缓存类库,比如ehcache、oscache等,需要设置hibernate.cache.provider_class,我们这里用ehcache,在2.1中就是
    hibernate.cache.provider_class=

    2022年5月23日
    58
  • 2021.12.13idea激活码_最新在线免费激活

    (2021.12.13idea激活码)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月30日
    49

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号