代码之家  ›  专栏  ›  技术社区  ›  Timmy

Python查找函数

  •  0
  • Timmy  · 技术社区  · 15 年前

    我想用mako设置一个查找函数。在模板上,我有

    <%!
        lookup = { 'key': function }
    %>
    
    <%def name="function()">
        Output
    </%def>
    

    所以我以后可以用

    <%def name="body()">
        ${lookup['key']()}
    </%def>
    

    我知道为什么它不工作,因为它首先运行,在方法被加载之前,但是我要如何设置它呢?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Mike Boers    15 年前

    我可以告诉你为什么它不起作用,但我在这一点上没有一个干净的解决方案。给定的模板编译成以下Python代码:

    # -*- encoding:utf-8 -*-
    from mako import runtime, filters, cache
    UNDEFINED = runtime.UNDEFINED
    __M_dict_builtin = dict
    __M_locals_builtin = locals
    _magic_number = 5
    _modified_time = 1285968547.0498569
    _template_filename='<snip>'
    _template_uri='<snip>'
    _template_cache=cache.Cache(__name__, _modified_time)
    _source_encoding='utf-8'
    _exports = ['function']
    
    
    # SOURCE LINE 1
    
    lookup = { 'key': function }
    
    
    def render_body(context,**pageargs):
        context.caller_stack._push_frame()
        try:
            __M_locals = __M_dict_builtin(pageargs=pageargs)
            __M_writer = context.writer()
            # SOURCE LINE 3
            __M_writer(u'\n\n')
            # SOURCE LINE 7
            __M_writer(u'\n')
            return ''
        finally:
            context.caller_stack._pop_frame()
    
    
    def render_function(context):
        context.caller_stack._push_frame()
        try:
            __M_writer = context.writer()
            # SOURCE LINE 5
            __M_writer(u'\n    Output\n')
            return ''
        finally:
            context.caller_stack._pop_frame()
    

    正如你所看到的 function 实际上被定义为 render_function . The Mako docs specify how to call defs from outside a template ,但它们没有指明如何在运行时正确地执行此操作。我链接的代码只是简单地查找 "render_%s" % name (见mako.模板,第217行),所以你 可以 考虑一下这样做。

        2
  •  1
  •   Mike DeSimone    15 年前

    也许你可以推迟查找 function

    <%!
        lookup = { 'key': lambda: function() }
    %>
    

    我没有使用Mako,但它在Python shell中工作:

    >>> x = lambda: foo()
    >>> x
    <function <lambda> at 0x10047e050>
    >>> x()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <lambda>
    NameError: global name 'foo' is not defined
    >>> def foo():
    ...    print "Test"
    ... 
    >>> x()
    Test