How do I get the filepath for a class in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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

Answers

http://docs.python.org/library/inspect.html#inspect.getfile http://docs.python.org/library/inspect.html#inspect.getfile

import inspect
inspect.getfile(C.__class__)

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/697320/how-do-i-get-the-filepath-for-a-class-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils