@@ -238,7 +238,8 @@ def maximum_line_length(physical_line, max_line_length, multiline, noqa):
238238
239239def blank_lines (logical_line , blank_lines , indent_level , line_number ,
240240 blank_before , previous_logical ,
241- previous_unindented_logical_line , previous_indent_level ):
241+ previous_unindented_logical_line , previous_indent_level ,
242+ lines ):
242243 r"""Separate top-level function and class definitions with two blank lines.
243244
244245 Method definitions inside a class are separated by a single blank line.
@@ -272,7 +273,20 @@ def blank_lines(logical_line, blank_lines, indent_level, line_number,
272273 if indent_level :
273274 if not (blank_before or previous_indent_level < indent_level or
274275 DOCSTRING_REGEX .match (previous_logical )):
275- yield 0 , "E301 expected 1 blank line, found 0"
276+ ancestor_level = indent_level
277+ nested = False
278+ # Search backwards for a def ancestor or tree root (top level).
279+ for line in lines [line_number - 2 ::- 1 ]:
280+ if line .strip () and expand_indent (line ) < ancestor_level :
281+ ancestor_level = expand_indent (line )
282+ nested = line .lstrip ().startswith ('def ' )
283+ if nested or ancestor_level == 0 :
284+ break
285+ if nested :
286+ yield 0 , "E306 expected 1 blank line before a " \
287+ "nested definition, found 0"
288+ else :
289+ yield 0 , "E301 expected 1 blank line, found 0"
276290 elif blank_before != 2 :
277291 yield 0 , "E302 expected 2 blank lines, found %d" % blank_before
278292 elif (logical_line and not indent_level and blank_before != 2 and
0 commit comments