When I run e.g. compile('sin(5) * cos(6)', '<string>', 'eval').co_names, I get ('sin', 'cos'), which is just what I expected.
But when I have a list comprehension in the expression, I get a little surprise: >>> compile('[x*x for x in y]', '<string>', 'eval').co_names ('_[1]', 'y', 'x') >>> This happens in Python 2.6.6 on Red Hat Linux, but not when I run Python 2.7.3 in Windows. Unfortunately I'm stuck with 2.6. * Are there more surprises similar to this one that I can expect from compile(...).co_names? Is this "behaviour" documented somewhere? * Is there perhaps a better way to achieve what I'm trying to do? What I'm really after, is to check that python expressions embedded in text files are: - well behaved (no syntax errors etc) - don't accidentally access anything it shouldn't - I serve them with the values they need on execution So, in the case of "a.b + x" I'm really just interested in a and x, not b. So the (almost) whole story is that I do: # Find names not starting with ".", i.e a & b in "a.c + b" abbr_expr = re.sub(r"\.\w+", "", expr) names = compile(abbr_expr, '<string>', 'eval').co_names # Python 2.6 returns '_[1]' in co_names for list comprehension. Bug? names = [name for name in names if re.match(r'\w+$', name)] for name in names: if name not in allowed_names: raise NameError('Name: %s not permitted in expression: %s' % (name, expr)) -- https://mail.python.org/mailman/listinfo/python-list