Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: __file__ of the caller

Tags:

python

I want to define a utility function f() in my module m such that

  1. if m.f() is invoked in /foo/a.py, it returns /foo/a.py
  2. if m.f() invoked in /bar/baz/b.py, it returns /bar/baz/b.py

Intuitively I'd explain f() as "it returns __file__ of the caller" but how can I really implement that (if possible at all?)

Note def f(): return __file__ returns /path/to/m.py wherever I call m.f() and that's not what I want.

like image 652
nodakai Avatar asked Jun 13 '16 14:06

nodakai


People also ask

How to get the caller of a python function?

The best way to get the caller of a Python function in a program is to use a debugger. As an alternative, if you want to get this info programmatically, you can analyze the call stack trace with the inspect package. I’ll show you both methods, and also present a third alternative - using an execution visualizer. Get The Caller Using a Debugger

How to print the path of the Hello module in Python?

First, we created the hello.py file that contains the printHello () method, which prints Hello World in the console. Then, we imported the hello module inside our main.py file and called the h.printHello () method. In the end, we printed the path of the file containing the hello module with the print (h.__file__) method.

What is the __call__ method in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x (arg1, arg2, ...) is a shorthand for x.__call__ (arg1, arg2, ...). Writing code in comment?

How do I find the current working directory in Python?

You can get the absolute path of the current working directory with os.getcwd () and the path specified with the python3 command with __file__. In Python 3.8 and earlier, the path specified by the python (or python3) command is stored in __file__.


3 Answers

some.py:

m.f()

m.py:

import inspect
import os

def f():
    return os.path.relpath(
            inspect.stack()[1][1],
            basePath)
    # returns path to caller file relative to some basePath
like image 104
Constantine Avatar answered Oct 18 '22 03:10

Constantine


__file__ is an attribute of the module loaded. So m.__file__ will always give the path of the file from which m was loaded. To make it work for any module, you should call the attribute for that particular module.

import module

def f(m): return m.__file__

print f(module)
like image 36
gaganso Avatar answered Oct 18 '22 02:10

gaganso


Take a look at the inspect module. It has a handy stack() method that returns the entire call stack, each element of which includes the filename. You just need to extract the last one.

like image 2
Anonymous Avatar answered Oct 18 '22 04:10

Anonymous