Equivalent to C bitmasks and enumerations

Wojtek Walczak gminick at bzt.bzt
Wed Apr 15 18:39:29 EDT 2009


On Wed, 15 Apr 2009 12:51:31 +0200, Ulrich Eckhardt wrote:

Hi,

> I'm currently using Python to implement a set of tests for code that is
> otherwise written in C. This code was wrapped using Boost.Python and is
> then loaded into Python as module.
...
> What I'm looking for is a suggestion how to handle this in Python. Note that
> technically, this works without problem, I'm rather looking for stylistic
> advise. What I currently have is these (note: I'm retyping this, so ignore
> any syntax errors, please):
...
> Any other suggestions how to structure this or rewrite this?

It's not exactly what you're searching for, but with a bit of work
it should fit your needs:

---------
class Colors(object):
   def __init__(self):
      self.colors_reg = {}
      self.colors_set = 0

   def register_color(self, name):
      self.colors_reg.setdefault(name, 1 << len(self.colors_reg))

   def set_color(self, name):
      self.colors_set |= self.colors_reg[name]

   def has_color(self, color):
      return bool(self.colors_reg[color]&self.colors_set)

   def status_as_string(self, st):
      tmp = []
      for k in self.colors_reg:
         if st & self.colors_reg[k]:
            tmp.append(k)
      return '|'.join(tmp)


c = Colors()
# register your colors
c.register_color('RED')
c.register_color('BLUE')
c.register_color('YELLOW')

# set colors 'on'
c.set_color('RED')
c.set_color('YELLOW')

print c.has_color('RED')
print c.has_color('BLUE')
print c.status_as_string(5)
--------

HTH,
-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/



More information about the Python-list mailing list