Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

__file__ is not defined in 'sourced' Python scripts #1283

Closed
kevinushey opened this issue Sep 27, 2022 · 2 comments · Fixed by #1284
Closed

__file__ is not defined in 'sourced' Python scripts #1283

kevinushey opened this issue Sep 27, 2022 · 2 comments · Fixed by #1284

Comments

@kevinushey
Copy link
Collaborator

For example, with the script:

print(__file__)

One can run the script in a standalone Python instance and see e.g.

$ python3 abc.py
/Users/kevin/scratch/abc.py

However, __file__ doesn't get defined for scripts sourced by reticulate:

> reticulate::source_python('~/scratch/abc.py')
Error in py_run_file_impl(file, local, convert) : 
  NameError: name '__file__' is not defined

Maybe py_run_file() should go through https://docs.python.org/3/c-api/veryhigh.html#c.PyRun_SimpleFile rather than https://docs.python.org/3/c-api/veryhigh.html#c.PyRun_StringFlags?

@kevinushey
Copy link
Collaborator Author

@t-kalinowski
Copy link
Member

t-kalinowski commented Sep 28, 2022

PyRun_SimpleFile unfortunately doesn't expose the locals and globals arguments, which we will need I think to maintain support for py_run_file(local = TRUE) usage.

PyRun_File does expose the globals and locals arguments, but it doesn't set __file__ and __cached__ for us. It looks like we'll have to do that manually. (PyRun_FileExFlags just reads compiles and goes straight to eval, with some error handling along the way. The only attr it ensures is __builtins__ if globals is main)

Something that's interesting is that in PyRun_SimpleFile, the __file__ item is deleted from the dictionary before returning. __file__ is only available during code execution. I think that makes sense if code is being evaluated in __main__, but I'm less sure if that's the correct behavior if we're evaluating in a local dict pseudo-module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants