local variable referenced before assignment

354 views
Skip to first unread message

Clodoaldo

unread,
Apr 27, 2007, 11:09:25 AM4/27/07
to Mako Templates for Python
I'm getting this error with the following code:
UnboundLocalError: local variable 'x' referenced before assignment

# -*- coding: utf-8 -*-
from mako.lookup import TemplateLookup

mylookup = TemplateLookup(
directories='./mako_templates',
#module_directory='./mako_templates',
input_encoding='utf-8',
output_encoding='utf-8',
default_filters=['decode.utf8'],
)
mytemplate = mylookup.get_template('mytmpl.txt')
print mytemplate.render(x='0')

## mytmpl.txt

<%
if x == 0:
x = 1
%>

${x}

This works:
## mytmpl.txt

<%
y = x
%>

${y}

What am I missing? Is there something special about the if in Python
blocks?

Regards, Clodoaldo Pinto Neto

Michael Bayer

unread,
Apr 27, 2007, 12:08:48 PM4/27/07
to mako-d...@googlegroups.com

On Apr 27, 2007, at 11:09 AM, Clodoaldo wrote:

> ## mytmpl.txt
>
> <%
> if x == 0:
> x = 1
> %>
>
> ${x}
>


its normal python. youre assigning to "x", which means its local to
the function youre inside of. therefore you cant reference it
beforehand.

def somefunction():


if x == 0:
x = 1

somefunction()

will raise the same error.

Clodoaldo

unread,
Apr 27, 2007, 12:32:25 PM4/27/07
to mako-d...@googlegroups.com
2007/4/27, Michael Bayer <mik...@zzzcomputing.com>:

Ok thanks. Now I found a work around it. But why this also does not work:?

## mytmpl.txt

<%
global x
if (x == 0):
x = 1
%>

${x}

Is the if inside his very own function?

Regards,
--
Clodoaldo Pinto Neto

Michael Bayer

unread,
Apr 27, 2007, 1:26:55 PM4/27/07
to mako-d...@googlegroups.com

On Apr 27, 2007, at 12:32 PM, Clodoaldo wrote:

> Ok thanks. Now I found a work around it. But why this also does not
> work:?
>
> ## mytmpl.txt
>
> <%
> global x
> if (x == 0):
> x = 1
> %>
>
> ${x}
>
> Is the if inside his very own function?
>

>>> def foo():
... global x
... if x == 0:
... x = 1
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
NameError: global name 'x' is not defined


Clodoaldo

unread,
Apr 27, 2007, 1:53:46 PM4/27/07
to mako-d...@googlegroups.com
2007/4/27, Michael Bayer <mik...@zzzcomputing.com>:

>>> x = 0


>>> def foo():
... global x
... if x == 0:
... x = 1

... return x
...
>>> foo()
1

Then how does that compares to:

print mytemplate.render(x=0)

<%
global x
if (x == 0):
x = 1
%>
${x}

Michael Bayer

unread,
Apr 27, 2007, 2:07:09 PM4/27/07
to mako-d...@googlegroups.com

On Apr 27, 2007, at 1:53 PM, Clodoaldo wrote:

> Then how does that compares to:
>
> print mytemplate.render(x=0)
>
> <%
> global x
> if (x == 0):
> x = 1
> %>
> ${x}
>

its the same thing. the "x" inside your context is not going to get
used because you have declared "x" explicitly.

Reply all
Reply to author
Forward
0 new messages