How do I detect if Twig is in debug mode?
I have found the solution to my question, by looking at the dump() function definition in the devel module. 

Passing the Twig_Environment object into my function, I can use the isDebug() method:

public function myfunction(\Twig_Environment $env, $string) {
  if($env-&gt;isDebug()) {
    $string = 'foobar';
  }
  return $string;
}