"return" in def

Steve Holden steve at holdenweb.com
Sun Dec 28 12:38:50 EST 2008


Roger wrote:
> Hi Everyone,
> 
> First I want to thank everyone that posts to this group.  I read it
> daily and always learn something new even if I never feel like I have
> anything to contribute but my questions.
> 
> When I define a method I always include a return statement out of
> habit even if I don't return anything explicitly:
> 
> def something():
>         # do something
>         return
> 
> Is this pythonic or excessive?  Is this an unnecessary affectation
> that only adds clock ticks to my app and would I be better off
> removing "returns" where nothing is returned or is it common practice
> to have returns.
> 
It's an unnecessary affectation, but I don't believe it adds any clock
ticks to your app, as the function has to return anyway. The dis module
shows you they both generate exactly the same code:

>>> from dis import dis
>>> def f1():
...   print "hello"
...
>>> def f2():
...   print "hello"
...   return
...
>>> dis(f1)
  2           0 LOAD_CONST               1 ('hello')
              3 PRINT_ITEM
              4 PRINT_NEWLINE
              5 LOAD_CONST               0 (None)
              8 RETURN_VALUE
>>> dis(f2)
  2           0 LOAD_CONST               1 ('hello')
              3 PRINT_ITEM
              4 PRINT_NEWLINE

  3           5 LOAD_CONST               0 (None)
              8 RETURN_VALUE
>>>


> Even when I'm not explicitly returning something I like to add
> "return" because it's a good additional visual marker for me to see
> where a method definition ends especially in cases where I may use a
> nested method.
> 
Well, I suppose at least you aren't writing "return None" ...
Normally a blank line or two suffices for me.

Take a look at PEP 8 for some discussion for Python coding style.

  http://www.python.org/dev/peps/pep-0008/

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list