How to know where an object was instantiated in python?
Question: I define a class in a given python module. From a few other python files I
will create instances of said class. The instances register themselves at
object creation, ie during `__init__()`, in a singleton registry object. From
a third type of python file I would like to access the registry, look at the
objects therein and be able to figure out in which files these objects were
created beforehand.

A code sample might look as follows:

Python module file : '/Users/myself/code/myobjectmodule.py':

    
    
    @singleton
    class Registry(object):
         def __init__(self):
             self.objects = {}
    
    class MyObject(object):
        def __init__(self, object_name):
            self.object_name = object_name
            Registry().objects[self.object_name] = self
    

`singleton` decorator according to
<http://www.python.org/dev/peps/pep-0318/#examples>

Instance creation python files :
'/Users/myself/code/instance_creation_python_file.py':

    
    
    from myobjectmodule import MyObject
    
    A = MyObject('Foo')
    

Third python file : '/Users/myself/code/registry_access.py':

    
    
    from myobjectmodule import Registry
    
    registry = Registry()
    foo = registry.objects['Foo']
    

Now, I would like to have a method `foo.get_file_of_object_creation()`.

How can I implement this method?

### Edit:

The reason for this approach is the following scenario:  
1\. A framework defines a set of objects that shall specify data sources and
contain the data after loading (MyObject).  
2\. Apps making use of this framework shall specify these objects and make use
of them. Each app is saved in a .py file or a folder that also specifies the
name of the app via its name.  
3\. An engine provides functionality for all apps, but needs to know, for some
features, which of the objects originate from which app / file.


Answer: All the caveats about this only being a good idea for debugging aside, you can
use the `inspect` module.

    
    
    import inspect
    
    def get_caller():
        return inspect.stack()[2]   # 1 is get_caller's caller
    
    def trace_call():
        _, filename, line, function, _, _ = get_caller()
        print("Called by %r at %r:%d" % (function, filename, line))
    
    def main():
        trace_call()
    
    main()
    

produces

    
    
    Called by 'main' at 'trace.py':11
    

