Be my human compiler: What is wrong with this Python 2.5 code?
My framewor开发者_如何学编程k is raising a syntax error when I try to execute this code:
from django.template import Template, TemplateSyntaxError
try:
Template(value)
except TemplateSyntaxError as error:
raise forms.ValidationError(error)
return value
And here's the error:
from template_field import TemplateTextField, TemplateCharField
File "C:\django\internal\..\internal\cmsplugins\form_designer\template_field.py", line 14
except TemplateSyntaxError as error:
^
SyntaxError: invalid syntax
What's going on?
The alternate syntax except SomeException as err
is new in 2.6. You should use except SomeException, err
in 2.5.
You can't have an empty try
block like that in Python. If you just want to do nothing in the block (for prototyping code, say), use the pass
keyword:
from django.template import Template, TemplateSyntaxError
try:
pass
except TemplateSyntaxError as error:
Template(value)
raise forms.ValidationError(error)
return value
Edit: This answers the original version of the question. I'll leave it up for posterity, but the question has now been edited, and @jleedev has the correct answer to the revised question.
You can't try nothing. If you really have nothing to try, use the pass
keyword:
try:
pass
except TemplateSyntaxError as error:
Template(value)
raise forms.ValidationError(error)
return value
But based on my (limited) knowledge of Django, I'd guess you want something like this instead:
try:
return Template(value)
except TemplateSyntaxError as error:
raise forms.ValidationError(error)
You've got nothing inside your try block. A try/except block looks like:
try:
do_something()
except SomeException as err:
handle_exception()
In every block in Python you should do something, or if you don't want to do something use the pass
statement!
精彩评论