Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the filepath for a class in Python?

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

like image 485
Staale Avatar asked Mar 30 '09 13:03

Staale


People also ask

How do I find the Filepath in Python?

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.

How do I get the file path of a string in Python?

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.

How do I get the full path of a file in Python?

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.


1 Answers

You can use the inspect module, like this:

import inspect inspect.getfile(C.__class__) 
like image 172
DNS Avatar answered Oct 05 '22 01:10

DNS