aragaer
aragaer

Reputation: 17848

Tornado locale.translate

Given a simple template I'm trying to add some i18n. But I'm getting the following error:

File "login_xhtml.generated.py", line 5, in _tt_execute
    _tt_tmp = _('Welcome')  # login.xhtml:4
UnboundLocalError: local variable '_' referenced before assignment
(<class 'UnboundLocalError'>, UnboundLocalError("local variable '_' referenced before assignment",), <traceback object at 0x7ffc50c957a0>)

For some reason, "_" is not defined in template generator. Even worse, it gets undefined somewhere in the process. I've tried adding "_" to my handler's namespace. I've tried printing the template namespace from tornado code right before "execute" is called to call template - "_" is present in namespace, but not in template code.

If I define something else as an alias to 'locale.translate' it does work as expected. Seems that problem is related to "_" only.

My final (rather desperate) attempt was to add the following line to tornado template code:

 def generate(self, writer):
     writer.write_line("def _tt_execute():", self.line)
     with writer.indent():
+        writer.write_line("_ = locale.translate", self.line)
         writer.write_line("_tt_buffer = []", self.line)
         writer.write_line("_tt_append = _tt_buffer.append", self.line)
         self.body.generate(writer)
         writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)

And that did work actually. However it doesn't seem a proper solution.

I do have the latest version of tornado (at least pip says so) - 3.1.1.

What could be the reason of this?

Note: I use python3. Could that be the cause of the problem?

Upvotes: 0

Views: 530

Answers (1)

jfs
jfs

Reputation: 414315

UnboundLocalError means that _ is assigned further in the code in the same local scope (a function as a rule) otherwise you would get NameError: global name '_' is not defined. You should remove any bindings for _ in your code. Interactive shell binds _, loop binds for _ in range(n), etc.

Upvotes: 1

Related Questions