is there any principle when writing python function

Terry Reedy tjreedy at udel.edu
Tue Aug 23 14:29:38 EDT 2011


On 8/23/2011 11:22 AM, Steven D'Aprano wrote:

> Even 7±2 is probably excessive: I find that I'm most comfortable with
> functions that perform 4±1 chunks of work. An example from one of my
> classes:
>
>      def find(self, prefix):
>          """Find the item that matches prefix."""
>          prefix = prefix.lower()  # Chunk #1
>          menu = self._cleaned_menu  # Chunk #2
>          for i,s in enumerate(menu, 1):  # Chunk #3
>              if s.lower().startswith(prefix):
>                  return i
>          return None  # Chunk #4
>
> So that's three one-line chunks and one three-line chunk.

In terms of different functions performed (see my previous post), I see
   attribute lookup
   assignment
   enumerate
   sequence unpacking
   for-looping
   if-conditioning
   lower
   startswith
   return
That is 9,  which is enough.

-- 
Terry Jan Reedy





More information about the Python-list mailing list