Why does this get a syntax error when exec() is called?
I have a 开发者_如何学Cdatabase of questions, and a few of those questions have need of special validation. So, I added a field to my model called py_validation and when those questions are answered, I validate them by running the code that is stored in py_validation. When I paste the code into the interpereter, it works correctly, but when I pass it into exec, it fails with the error:
Traceback (most recent call last):
File "<string>", line 2, in <fragment>
invalid syntax: <string>, line 2, pos 31
The code looks like:
# This code relies on the field type being a char field
if len(value.split('\n')) < 5:
raise ValidationError(_("You must specify at least 5 widgets, one per line"))
super(CharField, self).validate(value)
I'm calling it using:
def do_py_validate(field, value):
exec field.py_validation
so that variable value is in local scope while executing. Doesn't quite make sense that the code that works just fine, bails when executed like this.
Turns out to have a simple answer. The string contained \r characters that python was not happy swallowing. The answer came as I was trying to figure out how to make a file like object to read the string from. The solution is:
def do_py_validate(field, value):
exec field.py_validation.replace('\r', '')
This was almost as much fun as programming in Whitespace.
精彩评论