faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Boolean type

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 48, Michael P. Reilly


"""
Packages: new_datatypes
"""

"""
You want to be a bit more precise with the value of __flag.  It could get
corrupted later when just keeping the reference to some object.  And you
need to add the __nonzero__ method.
"""

class Bool:
  def __init__(self, flag=0):
      if flag:
          self.__flag = 1
      else:
          self.__flag = 0
  def __nonzero__(self):
      return self.__flag == 1
  def __cmp__(self, other):
      if (self.__flag and other) or (not self.__flag and not other):
        return 0
      else:
        return 1
  def __rcmp__(self, other):
      return -cmp(other, self.__flag)

"""
Adding a __nonzero__ method would get rid of the first clause in the
__cmp__ method and allow "if" and "while" statements:
  done = false
  while not done:
    ...
    done = true

The __init__corruption I describe above could come up in the form:
"""

ingredients = []
was_spam = Bool(ingredients)
ingredients.append( 'spam' )
if not was_spam:
    print 'There were no ingredients to make'

"""
This would not fall into the if statement if ingredients was stored in
the object as a reference.  Note that this can also be a side effect:
"""

ingredients = ['toast', 'spam', 'eggs', 'spam', 'spam', 'ham']
has_spam = Bool(ingredients)
while has_spam:
    print ingredients[0]
    del ingredients[0]

# The while loop ends when there are no items in the list.
# (Thus generating an error. -- PSST)