Implicit versus explicit return

I’m doing a bit of python right now, trying the Google Appengine .

Going from Ruby to Python is not really hard, they have lots of things in common. One error that got me, is that in Python, all return values are explicit. So instead of writing :

def render_template(name, vals)
  Template.render(File.join(templ_path, name + '.html'), vals)
end

you write :

def render_template(name, vals):
  return template.render(os.path.join(templ_path, name + '.html'), vals)

In python, if return is not given, a function returns Null by default.

It gets me thinking, what are the decisions behind this choice ?

Function

If you need to return a value, implicit return is nicer, because in higher-order functions, your block is often short, and it adds some characters. See:

arr2 = arr.map{|x| x.to_i}

versus

arr2 = map(lambda x: return int(x), arr)

Maybe this is why, in practice, python people tend to prefer for loops.

Procedure

If you don’t need to return a value, explicit return is nicer, because you’ll have to add a nil statement to keep the same interface.

def get(self):
  self.response.out.write(render_template('index'))

versus

def get
  response.out.write(render_template('index'))
  nil
end

In practice, ruby people don’t bother to add that extra nil statement. In most cases it doesn’t really hurt, but interfaces more often leak internal structures, which makes them harder to change later on.

Conclusion

Done with the unscientific rambling. Both have their uses. While not statically typed, python tends to favor strictness. Ruby tends to favor “out of your way” decisions. Both languages are coherent with their goals.