Functions do not return expressions. They return values. What the documentation says is that the value returned by bin
is a string that represents a valid python expression. In fact the returned value represents a binary literal.
You can check whether a string is a valid expression by evaluating it using eval
:
eval(text)
Warning: never call eval
on contents that you don't control (e.g. user provided strings) and avoid using it in general. It's a security hazard.
Note: There's also a ast.literal_eval
that is safer (i.e. when executed it will not anything bad so you can use it on user-provded text etc.) but only works for literal expressions (i.e. expressions without variables/method or function calls. Only literals and operators)
A better way to check it is by parsing it using the ast.parse
function:
ast.parse(text, mode='eval')
The mode='eval'
specifies to parse the content as an expression.
This is better because it avoids to execute the expression. If the function raises an exception is because the syntax isn't valid. If it succeeds then the text represents a valid python expression:
>>> import ast
>>> ast.parse('1+', mode='eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
1+
^
SyntaxError: unexpected EOF while parsing
>>> ast.parse('1+1', mode='eval')
<_ast.Expression object at 0x7f10376c4e10>
So you could use something like the following:
def is_valid_expr(expr):
try:
ast.parse(expr, mode='eval')
except SyntaxError:
return False
else:
return True
as in:
if is_valid_expr(some_text):
print("It's valid!")
else:
print("It's invalid!")
Formally a valid expression is defined by the python grammar (see the expr
non terminal). The ast.parse
function uses that grammar to parse its input.
Note: using ast.parse
you can check whether a string is valid python statement or generic code. Just use mode='single'
for a single statement and mode='exec'
for generic code.