How to get the path to a module file from a function executed, but not declared in it, in Python?

If I need a path to the current module, I will use __file__.

Now let's say I want the function to return this. I can not:

def get_path():
    return __file__

Since it will return the path to the module, the function has been declared.

I need it to work, even if the function is not called at the root of the module, but at any level of nesting.

0
source share
3 answers

Here's how I do it:

import sys

def get_path():
    namespace = sys._getframe(1).f_globals  # caller globals
    return namespace.get('__file__')
+2
source

Get it from globalsdict in this case:

def get_path():
    return globals()['__file__']

Change in response to comment: taking into account the following files:

# a.py
def get_path():
    return 'Path from a.py: ' + globals()['__file__']

# b.py
import a

def get_path():
    return 'Path from b.py: ' + globals()['__file__']

print get_path()
print a.get_path()

Running this will give me the following result:

C:\workspace>python b.py
Path from b.py: b.py
Path from a.py: C:\workspace\a.py

/ , ( , ), .

+1

I found a way to do this using the validation module. I am fine with this solution, but if someone finds a way to do this without dropping the whole stack, it would be cleaner, and I would gratefully accept his answer:

def get_path():
    frame, filename, line_number, function_name, lines, index =\
        inspect.getouterframes(inspect.currentframe())[1]
    return filename
0
source

Source: https://habr.com/ru/post/1766350/


All Articles