Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 714
phistakis Avatar asked Aug 01 '12 10:08

phistakis


People also ask

What is the __ file __ in Python?

__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system.

What does OS path dirname (__ FILE __)?

dirname() method in Python is used to get the directory name from the specified path.

What is OS path Realpath?

os.path. realpath(path, *, strict=False) Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system). If a path doesn't exist or a symlink loop is encountered, and strict is True , OSError is raised.

What OS module function should you use to get the path of the current working directory?

To return the directory you are currently in, we use the OS module to interact with the operating system. Under the OS module, we use the os. getcwd() method to return the path of the current directory.


1 Answers

This should do it:

inspect.getfile(sys._getframe(1))

sys._getframe(1) gets the caller frame, inspect.getfile(...) retrieves the filename.

like image 186
kay Avatar answered Nov 15 '22 16:11

kay