views:

212

answers:

3

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".

+7  A: 

try:

import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)
Jarret Hardie
+4  A: 

You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)
DNS
I think this will work for the Class, but not for an instance. inspect.getfile(c.__class__) should work, where c is an instance of C.
David Berger
You're right; I'd only ever used it on the class, and just assumed it would work for instances. Thanks!
DNS
+2  A: 

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

The typical Django app pattern is:

  • /project
    • /appname
      • models.py
      • views.py
      • /templates
        • index.html
        • etc.
Soviut
+1: Do what Django does naturally and life is so much simpler.
S.Lott
Agreed. Django is one of the frameworks with the least amount of "magic", but templates, template tags and apps have some expectations as part of their pattern. If you're having to do wacky class inference you're probably going in the wrong direction.
Soviut