0

Is it possible to get the name of the file containing the class? The variable exporter is a class in the below.

def main(exporter):

    v = exporter
    print v # <__main__.Vudu object at 0x106ea5210>
            # The class is "Vudu" and the filename that contains that class
            # is called vudu_exporter. How would I get "vudu_exporter" ?

Update: The following works to get the name of the script containing the class:

script_name = os.path.basename(inspect.getfile(v.__class__))
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

1

Call inspect.getfile on the class/function/method/module. It's not guaranteed to work, but it's more reliable than just checking the __file__ attribute of the object (for example, on Python 3.5, inspect.getfile(collections.defaultdict) works, while collections.defaultdict.__file__ raises AttributeError).

If you have an instance, this won't work without converting to the class first, e.g. inspect.getfile(type(instance)) (on Python 2, instance.__class__ can be more reliable with old-style classes); it can only tell you where the class was defined, not where the instance was defined.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271