Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out where an object has been instantiated?

Tags:

python

inspect

I'm trying to find out, at runtime, where an object has been instantiated, as this would enable providing a very useful error message to users of my library.

Suppose we have the following code:

import mylib

obj = mylib.MyClass()

obj is then passed to an instance of another class from mylib, and proceeds on a wonderful journey. Somewhere along the line, obj causes something bad to happen, and I'd like to point the user to where obj was instantiated.

I was hoping I could use the inspect module to find out in which file and at what line number obj was instantiated. Unfortunately, the inspect.getsourcefile and inspect.getsourcelines do not support instances. Is there a technical reason why this is not supported?

Is there another way I can obtain the data I'm looking for?

like image 288
Brecht Machiels Avatar asked Jan 19 '13 09:01

Brecht Machiels


1 Answers

You could record this information in your class's constructor:

import traceback

class MyClass(object):
   def __init__(self):
       self.traceback = traceback.extract_stack()[-2]

obj = MyClass()

print 'Instantiated in {0}:{1}'.format(*obj.traceback)
like image 192
NPE Avatar answered Nov 05 '22 13:11

NPE