Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get current script filename or path in python when instantiate a class?

# 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading