Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of the filename parameter of ast.parse?

The documentation reads:

ast.parse(source, filename='<unknown>', mode='exec')

    Equivalent to compile(source, filename, mode, ast.PyCF_ONLY_AST).


compile(source, filename, mode[, flags[, dont_inherit]])

    The filename argument should give the file from which the code was read;
    pass some recognizable value if it wasn’t read from a file
    ('<string>' is commonly used).

But it doesn't tell me much how to get this filename back from the AST node. Or how is this filename parameter is used. Is it just a stub?

like image 926
Vanuan Avatar asked Oct 21 '22 05:10

Vanuan


1 Answers

It sets the co_filename attribute on the code object, which is used to display the filename in tracebacks. Besides that, it's not really significant what value you pass.

>>> c = compile('raise Exception("spam")', 'eggs', 'exec')
>>> eval(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "eggs", line 1, in <module>
Exception: spam
like image 186
mata Avatar answered Nov 15 '22 07:11

mata