为什么未定义的变量大于mako模板中的数字?

时间:2012-02-02 07:11:54

标签: python mako

我使用名为x的变量,未定义x,并使用x与mako模板中的数字进行比较:

 %if x>5:
    <h1>helloworld</h1>
 %endif

为什么这句话不会导致异常或错误?但是,当我想打印出来时:

%if x>5:
    <h1>${x}</h1>
%endif

它引起了异常。为什么呢?

这是在mako。为什么我不能在IPython中使用这句话?因为如果我在IPython中使用未定义的变量,它会告诉我变量没有突然定义。

1 个答案:

答案 0 :(得分:6)

这是因为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

请注意,strict_undefinedmako.template.Template都提供mako.lookup.TemplateLookup

documentation的说明是:

  

替换不在Context中的任何未声明的变量的UNDEFINED的自动使用,并立即引发NameError。优点是立即报告包含名称的缺失变量。新的0.3.6。