WilliamKF
WilliamKF

Reputation: 43209

What is the defined behavior in Python for no return statement being reached?

Given the following Python code:

def avg(a):
  if len(a):
    return sum(a) / len(a)

What is the language defined behavior of avg when the length of a is zero or is its behavior unspecified by the language and thus should not be counted upon in Python code?

Upvotes: 1

Views: 133

Answers (2)

schesis
schesis

Reputation: 59238

If len(a) is 0, that will be treated as a False-like value, and your return statement won't be reached. When the flow of control drops out of the bottom of a function with no explicit return statement being reached, Python functions implicitly return None:

>>> print(avg([]))
None

If len(a) is not defined - in other words, if the object has no __len__() method - you'll get a TypeError:

>>> print(avg(False))
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in avg
TypeError: object of type 'bool' has no len()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125058

The default return value is None.

From the documentation on Calls:

A call always returns some value, possibly None, unless it raises an exception. How this value is computed depends on the type of the callable object.

Upvotes: 9

Related Questions