pythonperformance-testingcprofile

How do I pass in a self argument to python cProfile


I am trying to use cProfiling with python.

My python project has the following directory structure:

my-project
├── src
│   ├── lib 
│       └── app
│           └── data
│               └── car_sim.py
│
│
│
│
├── ptests 
│   ├── src 
│       └── lib 
│           └── app
│               └── data
│                   └── cprofile_test.py

I have a function inside car_sim.py that I want to cprofile and it is called "sim_text". It contains a function called:

#car_sim.py
import os

class RootSimulator:

    def sim_text(self, text):
            return text

I use the following code inside cprofile_test.py:

#cprofile_test.py
import cProfile
import pstats
import io

import src.lib.app.data.car_sim as car_sim_functions


pr = cProfile.Profile()
pr.enable()
text = 'my blabla sentence' #i can pass in this text below i guess...

#how do i pass to the below????!!
my_result = car_sim_functions.RootSimulator.sim_text()

pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('tottime')
ps.print_stats()

with open('test.txt', 'w+') as f:
    f.write(s.getvalue())

Now... when I run it using the command

python -m cProfile ptests/src/lib/app/data/cprofile_test.py

I get the following error:

TypeError: sim_text() missing 2 required positional arguments: 'self' and 'text'

My question is... It expects 2 args, so how do I pass in the "self" arg. For the 2nd arg, "text" I can pass in a value no problem.


Solution

  • class RootSimulator:
    
        def sim_text(self, text):
                return text
    

    Defines an instance method on instances of RootSimulator. You are trying to call sim_text from the class itself. You need to create an instance:

    simulator = car_sim_functions.RootSimulator()
    my_result = simulator.sim_text()
    

    If sim_text() does not actually need to be attached to an instance of the simulator, perhaps you don't need a class at all (just make it a plain function), or you could make it a static method:

    class RootSimulator:
    
        @staticmethod
        def sim_text(text):
                return text
    

    Note that it doesn't need self anymore.