# utils.py
class Foo:
def __init__():
print(__file__)
# mod.py
from utils import Foo
foo = Foo()
# This prints /absoulte/utils.py
# the expected output is /absoulte/mod.py
Is it possible to make the imported class Foo initialization with current file info instead of where it defined without passing the parameter?
>Solution :
Yes, it’s possible to determine the current file in which the class is used, rather than the file in which it’s defined. You can use the inspect module in the standard library to access information about the current stack frame and determine the file path.
Here’s an updated version of the Foo class that prints the file in which it’s used:
# utils.py
import inspect
class Foo:
def __init__(self):
frame = inspect.currentframe()
caller = frame.f_back
filename = inspect.getframeinfo(caller).filename
print(filename)
And here’s the usage in mod.py:
from utils import Foo
foo = Foo()
# This will now print /absolute/path/to/mod.py