Skip to content

Instantly share code, notes, and snippets.

@tiwijo
Created March 14, 2012 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiwijo/2039582 to your computer and use it in GitHub Desktop.
Save tiwijo/2039582 to your computer and use it in GitHub Desktop.
Do/While in Python
from functools import wraps
import inspect
def first(fn):
'''Wrap a function so True is returned the first time it is called.'''
@wraps(fn)
def wrapper(self, *args, **kwargs):
if self.first:
self.first = False
return True
return fn(self, *args, **kwargs)
return wrapper
class DoWhile(object):
'''A class that wraps a variable for one-time do while capabilities'''
def __init__(self, key):
'''Create the DoWhile. Grab a reference to the calling stack so that
the value of the variable (which lives in calling scope) with name
'key' can be retrieved.'''
self.locals = inspect.stack()[1][0].f_locals
self.first = True
self.key = key
@property
def value(self):
'''Get the current value of the variable in the parent scope.'''
return self.locals[self.key]
@first
def __lt__(self, other):
return self.value < other
@first
def __le__(self, other):
return self.value <= other
@first
def __eq__(self, other):
return self.value == other
@first
def __ne__(self, other):
return self.value != other
@first
def __gt__(self, other):
return self.value > other
@first
def __ge__(self, other):
return self.value >= other
@first
def __cmp__(self, other):
return self.value.__cmp__(other)
@first
def __nonzero__(self):
return self.value.__nonzero__()
abc = 5
dw = DoWhile('abc')
while dw > 6:
print 'this will show once'
abc = abc - 1
assert abc == dw.value
abc = 5
dw = DoWhile('abc')
print 'counting down from %d' % abc
while dw > 0:
print dw.value
abc = abc - 1
# OUTPUT
#
# $ python dowhile.py
# this will show once
# counting down from 5
# 5
# 4
# 3
# 2
# 1
@signed0
Copy link

signed0 commented Mar 15, 2012

What is this, Pascal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment