python's inspect.getfile returns "<string>"

Question:

Consider this code:

from sqlalchemy import exists
import inspect

print(inspect.getfile(exists))
# Effectively calls:
print(exists.__code__.co_filename)

On 2 systems I’ve tested it on it prints:

<string>
<string>

What does it mean? Could anything be done to get a proper filepath?

Asked By: sashkent3

||

Answers:

<string> means that the function was defined dynamically by executing a string, rather than being defined in the text of a file. You can see this if you do:

exec('def foo(): return 1')
print(inspect.getfile(foo))

I’m not sure why sqlAlchemy needs to define exists() this way. But I don’t think there’s any way to get the source file that does it.

Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.