Get the __file__ of the function one level up in the stack

Viewed 1190

I've found that I'm using this pattern a lot :

os.path.join(os.path.dirname(__file__), file_path)

so I've decided to put in a function in a file that has many such small utilities:

def filepath_in_cwd(file_path): 
    return os.path.join(os.path.dirname(__file__), file_path)

The thing is, __file__ returns the current file and therefore the current folder, and I've missed the whole point. I could do this ugly hack (or just keep writing the pattern as is):

def filepath_in_cwd(py_file_name, file_path): 
    return os.path.join(os.path.dirname(py_file_name), file_path)

and then the call to it will look like this:

filepath_in_cwd(__file__, "my_file.txt")

but I'd prefer it if I had a way of getting the __file__ of the function that's one level up in the stack. Is there any way of doing this?

1 Answers
Related