How to get file path for class in Python?

Given a class C in Python, how do you determine in which file the class was defined? I need something that can work either from class C or from an instance with C.

The reason I do this is because I'm generally a fan of posting files that belong to each other in the same folder. I want to create a class that uses a Django template to display itself as HTML. The base implementation should output the file name for the template based on the name of the file in which this class is defined.

Let's say I put the LocationArtifact class in the file "base / artifacts.py", then I want the default name to be specified is "base / LocationArtifact.html".

+54
python class introspection
Mar 30 '09 at 13:58
source share
3 answers

You can use the inspect module, for example:

import inspect inspect.getfile(C.__class__) 
+75
Mar 30 '09 at 14:14
source share
— -

to try:

 import sys, os os.path.abspath(sys.modules[LocationArtifact.__module__].__file__) 
+23
Mar 30 '09 at 14:05
source share

This is the wrong approach for Django and really forces things.

Typical Django Application Template:

  • /project
    • /app name
      • models.py
      • views.py
      • / patterns
        • index.html
        • and etc.
+4
Mar 30 '09 at 14:17
source share



All Articles