'Accessing script file location from an external file python

I have the following bizarre set up. Consider 3 scripts in different directories:

  • root1/folderA/scriptA.py
  • root2/folderB/scriptB.py
  • root2/folderC/scriptC.py

The first file and it's location are fully modifiable. The second and third are completely fixed.

scriptA.py contains a parent class:

class A:
    def get_path(self):
        # ...
        # code to determine "my_path"
        # ...
        return my_path

scriptB.py contains a child class:

from root1.folderA.scriptA import A

class B(A):
    pass

scriptC.py contains the code to execute:

from root2.folderB.scriptB import B

if __name__ == "__main__":
    b = B()
    print(b.get_path()) # want print root/folderB/scriptB.py

In scriptC.py what I want is the behaviour to get the path of the child class's declaration file (without any hard-coding). Is there any way to program the A.get_path() to have this behavoir?

I've tried looking into the inspect, os.path and pathlib modules but I haven't had any luck.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source