Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way of function with no return?

Tags:

python

pep8

A I couldn't find anything concerning in the PEP 8. I'm interested in your thoughts about the most pythonic syntax of function which have no return?

Are there any reason to prevent functions without a return line(example 3)?

Example 1:

def foo():
   print 'foo'
   return None

Example 2:

def foo():
   print 'foo'
   pass

Example 3:

def foo():
   print 'foo'
like image 649
T. Christiansen Avatar asked Nov 09 '12 11:11

T. Christiansen


People also ask

What happens if a function has no return?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

Is return None Pythonic?

Python returns null function | Example code Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing'). You can do this explicitly and return None yourself though.

What happens if u dont return a function Python?

So, if you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you. That default return value will always be None .

How do you use a function without return in Python?

In Python, it is possible to compose a function without a return statement. Functions like this are called void, and they return None, Python's special object for "nothing". Here's an example of a void function: >>> def sayhello(who): print 'Hello,', who + '!'


2 Answers

Keep it simple. Example 3 is the most pythonic way.

>>> import this

The Zen of Python, by Tim Peters

...
Simple is better than complex.
...
like image 77
b3orn Avatar answered Sep 22 '22 00:09

b3orn


The PEP8 has a recommendation on this topic:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None , and an explicit return statement should be present at the end of the function (if reachable).

Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)
like image 44
Vasili Syrakis Avatar answered Sep 20 '22 00:09

Vasili Syrakis