[Tutor] Understanding what the code does behind the scenes

Kent Johnson kent37 at tds.net
Fri Oct 16 14:21:06 CEST 2009

On Fri, Oct 16, 2009 at 7:21 AM, Dave Angel <davea at ieee.org> wrote:

> My attempt at readability  (untested):
> def colorPrint(color_items):       #1
>   """Call this function to print one or more strings, each with
>       a color number specified, to the console.  The argument
>       is a list of items, where each item is
>       a tuple consisting of a string and an integer color number,
>       with the color number determining what color the string
>       will be displayed in.  This function will not work with
>       redirection, as the color logic only works with the Win32 console."""
>   #2
>   for text, color in color_items:      #3
>       textcolor(color)          #4
>       print text                    #5

I would make the signature
def colorPrint(*color_items):

This was the caller doesn't need to enclose the arguments in a list,
it would be called like
colorPrint(('text', 0), ('more text', 1))

Another way to do this would be to make an object to hold the color
value and a print function that special cases it. A sketch:

class Style(object):
  def __init__(self, style):
    self.style = style
  def set_style(self):
    # Set the text color according to self.style

def colorPrint(*items):
  for item in items:
    if isinstance(item, Style):
      print item,

Now you can say
colorPrint(Style(0), 'some text', Style(1), 'some text in a different color')


More information about the Tutor mailing list