I want to define a utility function f()
in my module m
such that
m.f()
is invoked in /foo/a.py
, it returns /foo/a.py
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.
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
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.
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?
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__.
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
__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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With