Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.
The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.
Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".
To retrieve a file in Python, you need to know the exact path to reach the file, in Windows, you can view a particular file's path by right-clicking the File-> Properties-> General-> Location. Similarly, to run a script, the working directory needs to be set to the directory containing the script.
In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.
To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.
You can use the inspect module, like this:
import inspect inspect.getfile(C.__class__)
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