Reputation: 28008
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 of C
.
I am doing this because I am generally a fan of 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".
Upvotes: 140
Views: 85089
Reputation: 49
You can use the error to get the path of your class
import os
import traceback
class C:
def getClassPath(self):
#get foldet path
try:
raise ValueError("Example error")
except Exception as e:
tb = traceback.extract_tb(e.__traceback__)
return os.path.dirname(tb[-1].filename)
c = C()
print('path is',c.getClassPath())
Upvotes: -1
Reputation: 38219
You can use the inspect module, like this:
import inspect
inspect.getfile(C.__class__)
Upvotes: 191
Reputation: 91714
This is the wrong approach for Django and really forcing things.
The typical Django app pattern is:
Upvotes: 5
Reputation: 98072
try:
import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)
Upvotes: 54