Using __future__ imports in a Mako template

I have

<%!
    from __future__ import division
%>

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

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

What is the right way to do this?

+5
source share
2 answers

You cannot use expressions from __future__ importin Mako patterns. For everyone.

This is because the Mako template is compiled into a python file, and for this it sets some initial structures at the top of this 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 does the kit include any code from the template itself. Yours from __future__ import divisionwill never be placed first.

You can still use floating point division, either dropping the operand of the division operator /by float:

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

, , division .

+4

__future__ , , ( , -, Mako). Martijn , . , .

, . , .

, , . , :

<%!
    def div(a, b):
        return float(a) / float(b)
%>

Definitely less elegant than you meant, but it will work.

0
source

All Articles