Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django/Python, how can I find out which method called my method?

I would the first line of my method to be:

print "this method was called from "+filename_and_linenumber_of_code_that_called_it.

Is it possible to throw an exception, catch it immediately, and print a stack trace when a method is called?

like image 826
Deonomo Avatar asked Oct 25 '25 23:10

Deonomo


1 Answers

When i just want to make the code crash at some point to see the traceback, i just put "crash" in the code. Because it's not defined, it will crash, and i will see the traceback in django's exception page. If in addition, i use runserver_plus command provided by django-extensions (requires package werkzeug) then i get an AJAX shell at each frame of the stacktrace.

I understand you problem and I'm going to propose a professional method for dealing with this kind of problem. What you are trying to do is called "debugging" and there are tools for that.

Quickstart:

  1. run pip install ipython ipdb

  2. replace the print statement in your code by import ipdb; ipdb.set_trace()

  3. execute your code in runserver, it will pause and spawn a python shell where you can send command "up" to go to the previous stack frame (code that called your code). Type l if you want to see more lines of code.

Longer start: well actually i wrote a an overview of tools which help debugging python and django.

I disagree with other answers which propose to add more elaborate print statement. You want to be a good developer: you want to use a debugger. Be it werkzeug, pdb/ipdb, or GUIs, it doesn't matter as long as you can use it.

like image 172
jpic Avatar answered Oct 28 '25 15:10

jpic