Ben Mordecai
Ben Mordecai

Reputation: 695

Is it more pythonic to close a function with return or through indentation?

If I have a function that does not need to return a variable, is it considered better coding practice to close the function like this:

def foo():
    """Code"""
    return
# More code

or like this?

def bar():
   """Code"""
# More code

Upvotes: 3

Views: 133

Answers (3)

Jon Clements
Jon Clements

Reputation: 142146

Explicitlyreturn None when your function is mutating something else (eg. do_something_to_something()), or is an instance method of a class that mutates itself.

Make sure the behaviour is documented so it doesn't muck you/or anyone else up later though.

Upvotes: 0

user545424
user545424

Reputation: 16179

I think leaving out the return statement is the most pythonic thing to do. It makes it clear that the function wasn't designed to return anything and, more importantly, I think it just looks better.

def hello():
    print 'hello world'

versus

def hello():
    print 'hello world'
    return

Upvotes: 4

Russell Borogove
Russell Borogove

Reputation: 19037

I'd only use bare return for an early exit from the function. At the end of a function it leaves me wondering if you meant to return something and forgot to finish.

Upvotes: 3

Related Questions