Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know where an object was instantiated in Python?

Tags:

python

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.

like image 855
mhg Avatar asked Mar 03 '14 12:03

mhg


People also ask

How do you find the details of an object in Python?

In Python, you can get type information about an object with the built-in type() function. By type information I mean information about the class that implements the object. This tells you the object w1 is of type Weight. Now, you can use the type() function to check the type of anything.

What is __ base __ in Python?

Python provides a __bases__ attribute on each class that can be used to obtain a list of classes the given class inherits. The __bases__ property of the class contains a list of all the base classes that the given class inherits.

What does __ call __ do in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.

What method is called when a Python object is instantiated?

initializer method. A special method in Python (called __init__) that is invoked automatically to set a newly created object's attributes to their initial (factory-default) state. instance. An object whose type is of some class.


1 Answers

Without getting into the merits of why would you want to do this, here is a way to do it:

# assume the file is saved as "temp.py"

import inspect

class RegisteredObject(object):
    def __new__(cls, *args, **kwargs):
        new_instance = super(RegisteredObject, cls).__new__(cls, *args, **kwargs)
        stack_trace = inspect.stack()
        created_at = '%s:%d' % (
            stack_trace[1][1], stack_trace[1][2])
        new_instance.created_at = created_at 
        return new_instance

    def get_file_of_object_creation(self):
        return self.created_at

class MyObject(RegisteredObject):
    pass

def create_A():
    return MyObject()

def create_B():
    return MyObject()

if __name__ == '__main__':
    t1 = create_A()
    t2 = create_B()
    t3 = create_A()
    t4 = create_B()
    t5 = MyObject()
    print '"t1" was created at "%s"' % t1.get_file_of_object_creation()
    print '"t2" was created at "%s"' % t2.get_file_of_object_creation()
    print '"t3" was created at "%s"' % t3.get_file_of_object_creation()
    print '"t4" was created at "%s"' % t4.get_file_of_object_creation()
    print '"t5" was created at "%s"' % t5.get_file_of_object_creation()

Output:

$ python temp.py
"t1" was created at "temp.py:19"
"t2" was created at "temp.py:22"
"t3" was created at "temp.py:19"
"t4" was created at "temp.py:22"
"t5" was created at "temp.py:29"
like image 127
E.Z. Avatar answered Nov 03 '22 00:11

E.Z.