How to know where an object was instantiated in Python?

python inspect
python introspection function arguments
isfunction python
python inspect source code
code
inspect stack 1(3 in python)
python co_code
python stack frame

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.

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"

15. Classes and Objects — the Basics — How to Think Like a , Python is an object-oriented programming language, which means that it provides We'll shortly see how we can organize these together with the data. from turtle import Turtle tess = Turtle() # Instantiate objects of type Turtle alex = Turtle()� __init__ doesn’t return an object, but calling Foo(1, y=2) does return an object. Also, __init__ expects a self parameter, but there is no such parameter when calling Foo(1, y=2). There is something more complex at work here. In this post we’ll investigate together what happens when you instantiate a class in Python. Construction Sequence

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

Understanding Python Class Instantiation, Instantiating an object in Python consists of a few stages, but the I find that looking at the original source code is very interesting, but feel free� once the object has been instantiated. I want to check the inheritance hierarchy from the top-level __init__ while the object is being instantiated, and raise an exception if it fails my test. It seems from Heather's reply that it is not possible to do this directly, and therefore my inelegant solution is probably as good as any.

This answer is slightly different in that it does not use inspect.stack, considering I observed it to be particularly slow in Python 3.

import inspect


class Locatable:

    def __new__(cls, *_args, **_kwargs):
        # Background: http://eli.thegreenplace.net/2012/04/16/python-object-creation-sequence
        obj = super().__new__(cls)
        obj.location = obj._initialization_location()  # pylint: disable=protected-access
        return obj

    @staticmethod
    def _initialization_location():
        # Background: https://stackoverflow.com/a/42653524/
        frame = inspect.currentframe()
        while frame:
            if frame.f_code.co_name == '<module>':
                return {'module': frame.f_globals['__name__'], 'line': frame.f_lineno}
            frame = frame.f_back

    @property
    def name(self):
        module_name = self.__module__
        class_name = self.__class__.__qualname__  # pylint: disable=no-member
        return module_name + '.' + class_name

The above is a base class that can be inherited from.

The location attribute should contain the name of the module where the class is instantiated, e.g. mypackage.mymodule.

Object-Oriented Programming (OOP) in Python 3 – Real Python, You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see to how instantiate an object from a� Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. In this tutorial, you’ll learn the basics of object-oriented programming in Python. Conceptually, objects are like the components of a system. Think of a program as a factory assembly line of sorts.

Instantiation in Python - SyntaxDB, Used to create an object instance from a class (instantiate). Instantiation in Python. Used to See Also. Related. Constructor � Class Declaration and Structure. An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function,

Python Classes and Objects, Let's suppose there are 100 different dogs, then how would you know which element When an object of a class is created, the class is said to be instantiated. Creating an Object in Python. We saw that the class object could be used to access different attributes. It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call. >>> harry = Person() This will create a new object instance named harry. We can access the

How do I check if an object is an instance of a given class or of a , and can also check whether an object is one of Python's built-in types. Examples: if isinstance(obj, str): print repr(obj), "is an 8-bit string" if isinstance(obj,� An instantiated object is given a name and created in memory or on disk using the structure described within a class declaration. In C++ and other similar languages, to instantiate a class is to create an object, whereas in Java, to instantiate a class creates a specific class.

Comments
  • Why do you want to do this? Perhaps we can come up with some alternative solution, because this whole thing seems a little odd. That said, if you're really convinced you need this, take a look at the inspect module for what you need to figure out who is calling your init method.
  • Are you sure the file in which the object was created is really what you want? What if a program delegates all its MyObject creation to a utils.MyObjectMaker helper, and your registry sees all the objects as being created from /path/to/utils.pyc?