Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if code is getting executed as a function or using cell mode

I like to use cell mode rather than break points when writing/debugging functions.

How would you determine at run-time if the currently executing code is getting executed as a function or using cell mode?

Bonus Points If you can come up with a function that knows it is was invoked from within another function or from a cell.

An example of when this might be useful is when you want to load data differently during the execution of a function or if you want to create plotters for debugging. It becomes a pain to comment out specific lines when switching between executing as a cell or a function.

function doSomethingAwesome(inputs)
%%

if executingAsCell == true
  clear
  importData
end


% process stuff

if executingAsCell == true
   plot(myAwesomeResults)
end

Note, this is not a duplicate of my previous question: How to determine if code is executing as a script or function?

like image 740
slayton Avatar asked Nov 03 '22 05:11

slayton


1 Answers

The simplest approach is using dbstack() as suggested by @Junuxx:

if isempty(dbstack)
   %# true if you evaluated the cell while not in debug mode

Similarly, a function can know whether it was invoked from another function or from base/cell by checking the length of the dbstack

   function doSomething
   if length(dbstack)==1
      %# the function has been invoked from a cell or the command line
      %# (unless you're in debug mode)

A function can actually distinguish whether it was invoked from command-line or from a cell, since the latter doesn't write into the history:

   function doSomething

   if length(dbstack)==1
      javaHistory=com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory;
      lastCommand = javaHistory(end).toCharArray'; % ' added for SO code highlighting
      if strfind(lastCommand,'doSomething')
         %#  Probably invoked via command line
      else
         %#  Probably invoked via executing a cell

If you want to determine whether you're in debug mode or not, one possibility is to use the line-argument from dbstack, and check whether there is a call to the currently executing function on the line the apparent calling function.

like image 180
Jonas Avatar answered Nov 15 '22 08:11

Jonas