Search code examples
pythonmako

Using from __future__ import in Mako template


I have

<%!
    from __future__ import division
%>

at the very top of my template file. I get the error:

SyntaxError: from __future__ imports must occur at the beginning of the file 

What's the correct way to do this?


Solution

  • You cannot use from __future__ import statements in Mako templates. At all.

    This is because a Mako template is compiled to a python file, and in order for this to work it sets up some initial structures at the top of that python file:

    # -*- encoding:ascii -*-
    from mako import runtime, filters, cache
    UNDEFINED = runtime.UNDEFINED
    __M_dict_builtin = dict
    __M_locals_builtin = locals
    _magic_number = 7
    _modified_time = 1348257499.1626351
    _template_filename = '/tmp/mako.txt'
    _template_uri = '/tmp/mako.txt'
    _source_encoding = 'ascii'
    _exports = []
    

    Only after this initial setup is any code from the template itself included. Your from __future__ import division will never be placed first.

    You can still use floating point division by casting either operand of the / division operator to a float:

    >>> 1 / 2
    0
    >>> float(1) / 2
    0.5
    

    As long as you follow that workaround you can do fine without the division future import.