Alin Iuga
Alin Iuga

Reputation: 280

Is it possible to find out which instance of a certain class called a certain class method last when that class method is called by another instance?

Sorry for the long title. No idea how to ask it more concisely.

To avoid repeating the title, here is an example:

from random import choice

class Foo:
    def mymethod(self):
        # some code
        return
    def previous(self):
       ...

a = Foo()
b = Foo()
c = Foo()
d = Foo()
# etc ... 

for _ in range(10):
    x = choice([a, b, c, d])
    x.mymethod()
    x.previous()

What I am trying to achieve is make a class method previous() that prints/returns which instance of Foo() (a, b, c, d) called mymethod() right before the current instance called mymethod()


The WHY?

I have a script that makes HTTP requests to random endpoints of a certain host. These endpoints are different instances of the same class that uses a request() method to make the HTTP request.

There is a pandas DataFrame for each instance of this class (each endpoint) that holds data for each request such as response times. Along with this, I need the previous request that was made before the current request, hence my question.

Upvotes: 1

Views: 22

Answers (1)

jfaccioni
jfaccioni

Reputation: 7519

You can create a class variable which is updated whenever an instance calls mymethod - note that the class variable itself is updated, not a variable bound to any particular instance.

class Foo:
    previous = None 

    def mymethod(self): 
        # do something 
        self.__class__.previous = self

a = Foo()
b = Foo()

a.mymethod()
a.previous == a  # True
b.previous == a  # True
a.previous == b  # False

b.mymethod()
a.previous == a  # False
b.previous == b  # True

Upvotes: 1

Related Questions