python – 为什么未定义的变量大于mako模板中的数字?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 为什么未定义的变量大于mako模板中的数字?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1331字,纯文字阅读大概需要2分钟。
内容图文
![python – 为什么未定义的变量大于mako模板中的数字?](/upload/InfoBanner/zyjiaocheng/731/f60123f7f5324f47906d9ace69090fae.jpg)
我使用一个名为x的变量,x未定义,并使用x与mako模板中的数字进行比较:
%if x>5:
<h1>helloworld</h1>
%endif
为什么这句话不会导致异常或错误?但是当我想打印出来的时候:
%if x>5:
<h1>${x}</h1>
%endif
它引起了例外.为什么?
这是在mako.为什么我不能在IPython中使用这句话?因为如果我在IPython中使用未定义的变量,它会告诉我变量没有突然定义.
解决方法:
这是因为mako默认使用的Undefined对象只在渲染时失败,但可以在布尔表达式中使用,因为它实现了__nonzero__方法:
class Undefined(object):
"""Represents an undefined value in a template.
All template modules have a constant value
``UNDEFINED`` present which is an instance of this
object.
"""
def __str__(self):
raise NameError("Undefined")
def __nonzero__(self):
return False
UNDEFINED = Undefined()
要使用即使在布尔表达式中失败的未定义值,也可以使用strict_undefined参数,如下所示:
>>> from mako.template import Template
>>> mytemplate = Template("""%if x>5:
... <h1>helloworld</h1>
... %endif""", strict_undefined=True)
>>> mytemplate.render()
...
NameError: 'x' is not defined
请注意,在mako.template.Template和mako.lookup.TemplateLookup中都可以使用strict_undefined.
documentation的描述是:
Replaces the automatic usage of UNDEFINED for any undeclared variables not located in the Context with an immediate raise of NameError. The advantage is immediate reporting of missing variables which include the name. New in 0.3.6.
内容总结
以上是互联网集市为您收集整理的python – 为什么未定义的变量大于mako模板中的数字?全部内容,希望文章能够帮你解决python – 为什么未定义的变量大于mako模板中的数字?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。