比locals()或dict(foo = foo)更好的用于将上下文导出到模板引擎的功能 [英] Something better than locals() or dict(foo=foo) for exporting context to template engines

查看:50
本文介绍了比locals()或dict(foo = foo)更好的用于将上下文导出到模板引擎的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在#python关于为什么不使用本地人的简短讨论之后,我正在考虑一种没有dict(foo=foo,bar=bar)的重复性质(即不是DRY)的更好方法(或使用文字语法({})相同).

So, after a brief discussion on #python about why not to use locals, I was pondering about what would be a better way without the repetitive nature (i.e. not DRY) of dict(foo=foo,bar=bar) (or the same using the literal syntax ({})).

理想情况下,可以提交一个PEP(或已经存在)以反映 ecmascript和谐方案. (我想强调它传达的DRY方面).

Ideally, a PEP could be submitted (or one already exists) that mirrors this ecmascript harmony proposal. (I want to promote emphasis on the DRY aspect that it conveys).

那么,您有什么解决方案吗?我应该提交PEP吗?

So, do you have any solutions? Should I submit a PEP?

推荐答案

我目前为此提出的解决方案是以下模式.请告诉我这是否和使用locals()一样不好.

My currently proposed solution to this is the following pattern. Please tell me if this is just as bad of a practice as using locals().

class _Context:
    foo = 'bar'
render(request, 'example.html', vars(_Context))

一个警告是,对于python3来说这可能有点困难,因为它将使用具有不变的dictproxy的新型类,并且我需要查看它如何与给定的模板库交互.使用简单的'{foo}'.format(**_Context.__dict__)即可正常工作.

One caveat is that this might be a little iffy with python3 because it will use new-style classes with an immutable dictproxy, and I'd need to see how it would interact with the given templating library. Works fine with a simple '{foo}'.format(**_Context.__dict__).

locals()相比,它是的肯定改进,因为它相当明确,并且不会泄漏本地范围的其他部分.但是,它确实会泄漏旧样式类的'__module__''__doc__'以及新样式类的许多其他东西.

It is a definite improvement over locals(), since it's fairly explicit, and it doesn't leak other parts of the local scope. However, it does leak '__module__' and '__doc__' with old style classes and a bunch of other stuff with new-style classes.

这篇关于比locals()或dict(foo = foo)更好的用于将上下文导出到模板引擎的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆