仅在 Python 中获取函数作用域的本地字典

发布于 2024-07-20 02:48:33 字数 704 浏览 13 评论 0原文

我总是遇到这种情况,我想使用一本非常像“当地人”返回的字典,但它只包含函数有限范围内的变量。 有没有办法在 python 中做到这一点?

关于我为什么要这样做的更多信息:我正在使用 Django,当我去提供模板上下文时,我被迫要么手动创建字典(违反 DRY 原则),要么传入 locals()其中包含的条目比需要的多得多(浪费)。 django 是否缺少一些可以减轻 python 级别解决方案需求的东西?

澄清一下:

所以,我反复遇到的情况是:

@render_to('my_template.html') 
def myview(request): 
    var1 = #blahblah 
    var2 = #... 
    # do stuff with vars 
    return {'var1': val1,'var2':val2} 

所以我不会重复这些变量和命名约定,我会这样做:

@render_to('my_template.html') 
def myview(request): 
    var1 = #blahblah 
    var2 = #... 
    # do stuff with vars 
    return locals() 

我发现它更干净,但我知道它有点草率,因为大约有 30 个locals() 中的条目比我实际需要的更多。

I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python?

A bit more about why I want to do this: I'm playing with Django and when I go to give my templates context, I am forced either to either manually make a dictionary (In violation with DRY principles) or pass in locals() which contains far more entries then are needed (wasteful). Is there perhaps something I'm missing with django which would alleviate the need of a python level solution?

To Clarify:

So, the case that I've hit repeatedly is where I have:

@render_to('my_template.html') 
def myview(request): 
    var1 = #blahblah 
    var2 = #... 
    # do stuff with vars 
    return {'var1': val1,'var2':val2} 

So instead of repeating those variables and naming conventions, I'll do:

@render_to('my_template.html') 
def myview(request): 
    var1 = #blahblah 
    var2 = #... 
    # do stuff with vars 
    return locals() 

Which I find cleaner, but I know its kind of sloppy since there are about 30 more entries in locals() then I actually need.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浴红衣 2024-07-27 02:48:33

我不确定我是否同意制作字典违反了 DRY,但如果你真的不想重复任何内容,你可以在视图顶部定义一个“上下文”字典并使用字典键而不是整个视图中的变量。

def my_view(request):
    context = {}
    context['items'] = Item.objects.all()
    context['anothervalue'] = context['items'][2].name
    return render_to_response('template.html', context)

I'm not sure I agree that making a dictionary is a violation of DRY, but if you really don't want to repeat anything at all, you could just define a 'context' dictionary at the top of the view and use dictionary keys instead of variables throughout the view.

def my_view(request):
    context = {}
    context['items'] = Item.objects.all()
    context['anothervalue'] = context['items'][2].name
    return render_to_response('template.html', context)
半城柳色半声笛 2024-07-27 02:48:33

传递字典怎么会违反 DRY 呢? Django 就是 DRY,所以我怀疑它的标准行为会直接违反它。 然而,无论哪种情况,我都会使用 django-annoying 的修改版本让整个事情变得更容易:

@render_to('my_template.html')
def myview(request):
    # figure stuff out...
    return {'var1':'val1','var2','val2'}

render_to 装饰器负责处理请求上下文和所有这些好东西。 效果很好。

如果这没有帮助,我建议重新表述你的问题。 无论你想用 locals() 做什么,这样的事情很少有必要,特别是在 Django 的这种情况下。

How is passing a dictionary a violation of DRY? Django is all about DRY, so I doubt the standard behavior of it would directly violate it. In either case, however, I use a modified version of django-annoying to make the whole thing easier:

@render_to('my_template.html')
def myview(request):
    # figure stuff out...
    return {'var1':'val1','var2','val2'}

The render_to decorator takes care of the request context and all that good stuff. Works well.

If this doesn't help, I suggest rephrasing your question. Whatever you want to do messing around with locals() and such is rarely necessary especially in this kind of situation with Django.

平生欢 2024-07-27 02:48:33

你说你不喜欢使用 locals() 因为它是“浪费”。 浪费什么? 我相信它返回的字典已经存在,它只是给你一个参考。 即使它必须创建字典,这也是 Python 中优化程度最高的操作之一,所以不用担心。

您应该关注最能表达您的意图且出错可能性最小的代码结构。 您所担心的浪费是无需担心的。

You say you don't like using locals() because it is "wasteful". Wasteful of what? I believe the dictionary it returns already exists, it's just giving you a reference to it. And even if it has to create the dictionary, this is one of the most highly optimized operations in Python, so don't worry about it.

You should focus on the code structure that best expresses your intention, with the fewest possibilities for error. The waste you are worried about is nothing to worry about.

黑白记忆 2024-07-27 02:48:33

虽然我同意许多其他受访者的观点,即传递 locals() 或完全指定的字典 {'var1':var1, 'var2': var2} 很可能是可以的,如果您特别想对诸如 locals() 之类的字典进行“子集化”,这也远非困难,例如:

loc = locals()
return dict((k,loc[k]) for k in 'var1 var2'.split())

While I agree with many other respondents that passing either locals() or a fully specified dict {'var1':var1, 'var2': var2} is most likely OK, if you specifically want to "subset" a dict such as locals() that's far from hard either, e.g.:

loc = locals()
return dict((k,loc[k]) for k in 'var1 var2'.split())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文