By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,001 Members | 1,176 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,001 IT Pros & Developers. It's quick & easy.

Pending: A Mixin class for testing

P: n/a
Here is a Mix-in class I just built for testing.
It is quite simple, but illustrates how Mixins
can be used.

class Pending(object):
_pending = iter(())
def __new__(class_, *args, **kwargs):
try:
return class_._pending.next()
except StopIteration:
return super(Pending, class_).__new__(class_,
*args, **kwargs)

Now for the use:

class Float(Pending, float): pass

Float._pending = iter(range(4,7))

print [Float(x*(x+1)//2) for x in range(6)]

Possibly by using itertools functions such as chain as in:
Klass._pending = itertools.chain(generate_some(), Klass._pending)
you can inject fixed values to simplify testing.

Or something like this:

class SomeTrickyClass(...): # new-style only (derived from object)
...

class Hacked(Pending, SomeTrickyClass):
_pending = sample_value_generator()

TempHold, SomeTrickyClass = SomeTrickyClass, Hacked
try:
<do the test>
finally:
SomeTrickyClass = TempHold
--Scott David Daniels
sc***********@acm.org
Nov 26 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Scott David Daniels wrote:
Here is a Mix-in class I just built for testing.
It is quite simple, but illustrates how Mixins
can be used.

class Pending(object):
_pending = iter(())
def __new__(class_, *args, **kwargs):
try:
return class_._pending.next()
except StopIteration:
return super(Pending, class_).__new__(class_,
*args, **kwargs)

Now for the use:

class Float(Pending, float): pass

Float._pending = iter(range(4,7))

print [Float(x*(x+1)//2) for x in range(6)]

Possibly by using itertools functions such as chain as in:
Klass._pending = itertools.chain(generate_some(), Klass._pending)
you can inject fixed values to simplify testing.
If you're willing to allow for issubclass() to fail you can do without a
mixin:

from itertools import chain, repeat

def preload(class_, iterable):
items = chain(
(lambda *args, **kw: item for item in iterable), repeat(class_))
return lambda *args, **kw: items.next()(*args, **kw)

float = preload(float, "ABC")
print [float(x) for x in range(6)]
issubclass(float, float) # TypeError

Argh :-)

Peter
Nov 27 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.