Skip to content

Return or Yield Outside Function

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: return-or-yield-outside-function

Section titled “Sourcery refactoring id: return-or-yield-outside-function”

Remove return or yield statements found outside function definitions.

for i in range(10):
print(i)
return i
for i in range(10):
print(i)

If you intend to return or yield some value, make sure that the statement is correctly placed and indented in your code:

Before:

def square(x):
y = x**2
return y

After:

def square(x):
y = x**2
return y

The return and yield statements can only be used inside function definitions. Using them outside this context, or inside nested class definitions, is a SyntaxError.

This error may be very easy to pass through since sometimes it is caused by a wrong indentation.