What do you use as symbols for Python ?
bruno at modulix
onurb at xiludom.gro
Thu Nov 10 08:14:19 EST 2005
Pierre Barbier de Reuille wrote:
> When you need some symbols in your program, what do you use in Python ?
>
> For example, an object get a state. This state is more readable if
> expressed as a symbols, for example "opened", "closed", "error".
> Typically, in C or C++, I would use an enum for that:
> enum OBJECT_STATE
> {
> opened, closed, error
> }
>
> In CAML or Haskell I would use the union types:
>
> type ObjectState = Opened | Closed | Error
>
> In Ruby I would use the symbols :
>
> object.state = :opened
> object.state = :closed
> object.state = :error
>
> ... but I don't know what to use in Python !
Depends on the job... If I need to do bitmask operations, I'll use
integer flags. If I want the symbol to be human-readable, I'll use
strings. But everything in Python being an object, you can use whatever
seems appropriate....
Since we're in a 'state' exemple, here's a possible state pattern
implementation:
class MyObject(object):
def __init__(self, name):
self.name = name
self.__class__ = ClosedState
state = property(fget=lambda self: self.__class__)
def open(self, arg):
if arg == 1:
self.__class__ = OpenedState
else:
self.__class__ = ErrorState
def close(self):
self.__class__ = ClosedState
class OpenedState(MyObject):pass
class ClosedState(MyObject):pass
class ErrorState(MyObject):pass
m = MyObject('toto')
assert m.state is ClosedState
m.open(1)
assert m.state is OpenedState
m.close()
assert m.state is ClosedState
m.open(2)
assert m.state is ErrorState
I made states 'dummy' objects, but you could make this a real state
pattern implementation by defining default methods in the base class and
overriding appropriate methods in the 'state' subclasses.
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list