update from atlas
This commit is contained in:
parent
290079ec9a
commit
104b2c9d2d
@ -31,24 +31,24 @@ Card(rank='Q', suit='hearts')
|
||||
2 Card(rank='3', suit='spades')
|
||||
3 Card(rank='4', suit='spades')
|
||||
...
|
||||
>>> def alt_color_rank(card):
|
||||
>>> suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
|
||||
>>> def spades_high(card):
|
||||
... rank_value = FrenchDeck.ranks.index(card.rank)
|
||||
... suits = 'diamonds clubs hearts spades'.split()
|
||||
... return rank_value * len(suits) + suits.index(card.suit)
|
||||
... return rank_value * len(suit_values) + suit_values[card.suit]
|
||||
|
||||
Rank test:
|
||||
|
||||
>>> alt_color_rank(Card('2', 'diamonds'))
|
||||
>>> spades_high(Card('2', 'clubs'))
|
||||
0
|
||||
>>> alt_color_rank(Card('A', 'spades'))
|
||||
>>> spades_high(Card('A', 'spades'))
|
||||
51
|
||||
|
||||
>>> for card in sorted(deck, key=alt_color_rank): # doctest: +ELLIPSIS
|
||||
>>> for card in sorted(deck, key=spades_high): # doctest: +ELLIPSIS
|
||||
... print(card)
|
||||
Card(rank='2', suit='diamonds')
|
||||
Card(rank='2', suit='clubs')
|
||||
Card(rank='2', suit='diamonds')
|
||||
Card(rank='2', suit='hearts')
|
||||
...
|
||||
Card(rank='A', suit='clubs')
|
||||
Card(rank='A', suit='diamonds')
|
||||
Card(rank='A', suit='hearts')
|
||||
Card(rank='A', suit='spades')
|
18
02-array-seq/listcomp_speed.py
Normal file
18
02-array-seq/listcomp_speed.py
Normal file
@ -0,0 +1,18 @@
|
||||
import timeit
|
||||
|
||||
TIMES = 10000
|
||||
|
||||
SETUP = """
|
||||
symbols = '$¢£¥€¤'
|
||||
def non_ascii(c):
|
||||
return c > 127
|
||||
"""
|
||||
|
||||
def clock(label, cmd):
|
||||
res = timeit.repeat(cmd, setup=SETUP, number=TIMES)
|
||||
print(label, *('{:.3f}'.format(x) for x in res))
|
||||
|
||||
clock('listcomp :', '[ord(s) for s in symbols if ord(s) > 127]')
|
||||
clock('listcomp + func :', '[ord(s) for s in symbols if non_ascii(ord(s))]')
|
||||
clock('filter + lambda :', 'list(filter(lambda c: c > 127, map(ord, symbols)))')
|
||||
clock('filter + func :', 'list(filter(non_ascii, map(ord, symbols)))')
|
@ -1,22 +0,0 @@
|
||||
def deco_alpha(func):
|
||||
print('<<100>> deco_alpha')
|
||||
|
||||
def inner_alpha():
|
||||
print('<<200>> deco_alpha')
|
||||
func()
|
||||
|
||||
return inner_alpha
|
||||
|
||||
|
||||
def deco_beta(cls):
|
||||
print('<<300>> deco_beta')
|
||||
|
||||
def inner_beta(self):
|
||||
print('<<400>> inner_beta')
|
||||
print("result from 'deco_beta::inner_beta'")
|
||||
|
||||
cls.method3 = inner_beta
|
||||
return cls
|
||||
|
||||
|
||||
print('<<500>> evaldecos mudule body')
|
25
21-class-metaprog/evalsupport.py
Normal file
25
21-class-metaprog/evalsupport.py
Normal file
@ -0,0 +1,25 @@
|
||||
print('<[100]> evalsupport module start')
|
||||
|
||||
def deco_alpha(cls):
|
||||
print('<[200]> deco_alpha')
|
||||
|
||||
def inner_1(self):
|
||||
print('<[300]> deco_alpha:inner_1')
|
||||
|
||||
cls.method_y = inner_1
|
||||
return cls
|
||||
|
||||
# BEGIN META_ALEPH
|
||||
class MetaAleph(type):
|
||||
print('<[400]> MetaAleph body')
|
||||
|
||||
def __init__(self, name, bases, dic):
|
||||
print('<[500]> MetaAleph.__init__')
|
||||
|
||||
def inner_2(self):
|
||||
print('<[600]> MetaAleph.__init__:inner_2')
|
||||
|
||||
self.method_z = inner_2
|
||||
# END META_ALEPH
|
||||
|
||||
print('<[700]> evalsupport module end')
|
@ -1,92 +1,49 @@
|
||||
import atexit
|
||||
from evalsupport import deco_alpha
|
||||
|
||||
from evaldecos import deco_alpha
|
||||
from evaldecos import deco_beta
|
||||
print('<[1]> evaltime module start')
|
||||
|
||||
|
||||
print('<<1>> start')
|
||||
class ClassOne():
|
||||
print('<[2]> ClassOne body')
|
||||
|
||||
def __init__(self):
|
||||
print('<[3]> ClassOne.__init__')
|
||||
|
||||
func_A = lambda: print('<<2>> func_A')
|
||||
def __del__(self):
|
||||
print('<[4]> ClassOne.__del__')
|
||||
|
||||
def method_x(self):
|
||||
print('<[5]> ClassOne.method_x')
|
||||
|
||||
def func_B():
|
||||
print('<<3>> func_B')
|
||||
|
||||
def func_C():
|
||||
print('<<4>> func_C')
|
||||
|
||||
return func_C
|
||||
class ClassTwo(object):
|
||||
print('<[6]> ClassTwo body')
|
||||
|
||||
|
||||
@deco_alpha
|
||||
def func_D():
|
||||
print('<<6>> func_D')
|
||||
class ClassThree():
|
||||
print('<[7]> ClassThree body')
|
||||
|
||||
def method_y(self):
|
||||
print('<[8]> ClassThree.method_y')
|
||||
|
||||
|
||||
def func_E():
|
||||
print('<<7>> func_E')
|
||||
class ClassFour(ClassThree):
|
||||
print('<[9]> ClassFour body')
|
||||
|
||||
|
||||
class ClassOne(object):
|
||||
print('<<7>> ClassOne body')
|
||||
|
||||
def __init__(self):
|
||||
print('<<8>> ClassOne.__init__')
|
||||
|
||||
def __del__(self):
|
||||
print('<<9>> ClassOne.__del__')
|
||||
|
||||
def method1(self):
|
||||
print('<<10>> ClassOne.method')
|
||||
return "result from 'ClassOne.method1'"
|
||||
|
||||
class ClassTwo(object):
|
||||
print('<<11>> ClassTwo body')
|
||||
|
||||
|
||||
@deco_beta
|
||||
class ClassThree(ClassOne):
|
||||
print('<<12>> ClassThree body')
|
||||
|
||||
def method3(self):
|
||||
print('<<13>> ClassOne.method')
|
||||
return "result from 'ClassThree.method3'"
|
||||
|
||||
|
||||
if True:
|
||||
print("<<14>> 'if True'")
|
||||
|
||||
|
||||
if False:
|
||||
print("<<15>> 'if False'")
|
||||
|
||||
|
||||
atexit.register(func_E)
|
||||
|
||||
print("<<16>> right before 'if ... __main__'")
|
||||
def method_y(self):
|
||||
print('<[10]> ClassFour.method_y')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('<<17>> start __main__ block')
|
||||
print(func_A)
|
||||
print(func_A())
|
||||
print('<<18>> continue __main__ block')
|
||||
print(func_B)
|
||||
b_result = func_B()
|
||||
print(b_result)
|
||||
print('<[11]> ClassOne tests', 30 * '.')
|
||||
one = ClassOne()
|
||||
one.method1()
|
||||
b_result()
|
||||
print(func_D)
|
||||
func_D()
|
||||
one.method_x()
|
||||
print('<[12]> ClassThree tests', 30 * '.')
|
||||
three = ClassThree()
|
||||
three.method3()
|
||||
|
||||
class ClassFour(object):
|
||||
print('<<19>> ClasFour body')
|
||||
|
||||
print('<<20>> end __main__ block')
|
||||
three.method_y()
|
||||
print('<[13]> ClassFour tests', 30 * '.')
|
||||
four = ClassFour()
|
||||
four.method_y()
|
||||
|
||||
|
||||
print('<<21>> The End')
|
||||
print('<[14]> evaltime module end')
|
||||
|
53
21-class-metaprog/evaltime_meta.py
Normal file
53
21-class-metaprog/evaltime_meta.py
Normal file
@ -0,0 +1,53 @@
|
||||
from evalsupport import deco_alpha
|
||||
from evalsupport import MetaAleph
|
||||
|
||||
print('<[1]> evaltime_meta module start')
|
||||
|
||||
|
||||
@deco_alpha
|
||||
class ClassThree():
|
||||
print('<[2]> ClassThree body')
|
||||
|
||||
def method_y(self):
|
||||
print('<[3]> ClassThree.method_y')
|
||||
|
||||
|
||||
class ClassFour(ClassThree):
|
||||
print('<[4]> ClassFour body')
|
||||
|
||||
def method_y(self):
|
||||
print('<[5]> ClassFour.method_y')
|
||||
|
||||
|
||||
class ClassFive(metaclass=MetaAleph):
|
||||
print('<[6]> ClassFive body')
|
||||
|
||||
def __init__(self):
|
||||
print('<[7]> ClassFive.__init__')
|
||||
|
||||
def method_z(self):
|
||||
print('<[8]> ClassFive.method_y')
|
||||
|
||||
|
||||
class ClassSix(ClassFive):
|
||||
print('<[9]> ClassSix body')
|
||||
|
||||
def method_z(self):
|
||||
print('<[10]> ClassSix.method_y')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('<[11]> ClassThree tests', 30 * '.')
|
||||
three = ClassThree()
|
||||
three.method_y()
|
||||
print('<[12]> ClassFour tests', 30 * '.')
|
||||
four = ClassFour()
|
||||
four.method_y()
|
||||
print('<[13]> ClassFive tests', 30 * '.')
|
||||
five = ClassFive()
|
||||
five.method_z()
|
||||
print('<[14]> ClassSix tests', 30 * '.')
|
||||
six = ClassSix()
|
||||
six.method_z()
|
||||
|
||||
print('<[15]> evaltime_meta module end')
|
@ -9,12 +9,12 @@ record_factory: create simple classes just for holding data fields
|
||||
>>> name, weight, _ = rex # <3>
|
||||
>>> name, weight
|
||||
('Rex', 30)
|
||||
>>> "{2}'s dog weights {1}kg".format(*rex)
|
||||
>>> "{2}'s dog weights {1}kg".format(*rex) # <4>
|
||||
"Bob's dog weights 30kg"
|
||||
>>> rex.weight = 32 # <4>
|
||||
>>> rex.weight = 32 # <5>
|
||||
>>> rex
|
||||
Dog(name='Rex', weight=32, owner='Bob')
|
||||
>>> Dog.__mro__ # <5>
|
||||
>>> Dog.__mro__ # <6>
|
||||
(<class 'factories.Dog'>, <class 'object'>)
|
||||
|
||||
# END RECORD_FACTORY_DEMO
|
||||
@ -22,29 +22,29 @@ record_factory: create simple classes just for holding data fields
|
||||
|
||||
# BEGIN RECORD_FACTORY
|
||||
def record_factory(cls_name, field_names):
|
||||
if isinstance(field_names, str): # <1>
|
||||
if isinstance(field_names, str):
|
||||
field_names = field_names.replace(',', ' ').split()
|
||||
__slots__ = tuple(field_names)
|
||||
field_names = tuple(field_names) # <1>
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, *args, **kwargs): # <2>
|
||||
attrs = dict(zip(self.__slots__, args))
|
||||
attrs.update(kwargs)
|
||||
for name, value in attrs.items():
|
||||
setattr(self, name, value)
|
||||
|
||||
def __iter__(self):
|
||||
def __iter__(self): # <3>
|
||||
for name in self.__slots__:
|
||||
yield getattr(self, name)
|
||||
|
||||
def __repr__(self):
|
||||
def __repr__(self): # <4>
|
||||
values = ', '.join('{}={!r}'.format(*i) for i
|
||||
in zip(self.__slots__, self))
|
||||
return '{}({})'.format(self.__class__.__name__, values)
|
||||
|
||||
cls_attrs = dict(__slots__ = __slots__,
|
||||
__init__ = __init__,
|
||||
__iter__ = __iter__,
|
||||
__repr__ = __repr__)
|
||||
cls_attrs = dict(__slots__ = field_names, # <5>
|
||||
__init__ = __init__,
|
||||
__iter__ = __iter__,
|
||||
__repr__ = __repr__)
|
||||
|
||||
return type(cls_name, (object,), cls_attrs)
|
||||
return type(cls_name, (object,), cls_attrs) # <6>
|
||||
# END RECORD_FACTORY
|
||||
|
@ -1,4 +0,0 @@
|
||||
[pep8]
|
||||
ignore = E127,E302
|
||||
# E127: continuation line over-indented for visual indent
|
||||
# E302: expected 2 blank lines, found 1
|
@ -29,11 +29,11 @@ instance::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
||||
['_Quantity:0', '_Quantity:1', '__class__', ...
|
||||
['_Quantity#0', '_Quantity#1', '__class__', ...
|
||||
'description', 'price', 'subtotal', 'weight']
|
||||
>>> getattr(raisins, '_Quantity:0')
|
||||
>>> getattr(raisins, '_Quantity#0')
|
||||
10
|
||||
>>> getattr(raisins, '_Quantity:1')
|
||||
>>> getattr(raisins, '_Quantity#1')
|
||||
6.95
|
||||
|
||||
"""
|
||||
@ -47,7 +47,7 @@ class Quantity:
|
||||
cls = self.__class__ # <2>
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}:{}'.format(prefix, index) # <3>
|
||||
self.storage_name = '_{}#{}'.format(prefix, index) # <3>
|
||||
cls.__counter += 1 # <4>
|
||||
|
||||
def __get__(self, instance, owner): # <5>
|
||||
|
@ -29,21 +29,20 @@ instance::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
||||
['_Quantity:0', '_Quantity:1', '__class__', ...
|
||||
['_Quantity#0', '_Quantity#1', '__class__', ...
|
||||
'description', 'price', 'subtotal', 'weight']
|
||||
>>> getattr(raisins, '_Quantity:0')
|
||||
>>> getattr(raisins, '_Quantity#0')
|
||||
10
|
||||
>>> getattr(raisins, '_Quantity:1')
|
||||
>>> getattr(raisins, '_Quantity#1')
|
||||
6.95
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.price # doctest: +ELLIPSIS
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<bulkfood_v4b.Quantity object at 0x...>
|
||||
>>> br_nuts = LineItem('Brazil nuts', 10, 34.95)
|
||||
>>> br_nuts.price
|
||||
34.95
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Quantity#0'
|
||||
|
||||
"""
|
||||
|
||||
@ -56,7 +55,7 @@ class Quantity:
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}:{}'.format(prefix, index)
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
|
@ -29,21 +29,21 @@ instance::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
||||
['_Quantity:0', '_Quantity:1', '__class__', ...
|
||||
['_Quantity#0', '_Quantity#1', '__class__', ...
|
||||
'description', 'price', 'subtotal', 'weight']
|
||||
>>> getattr(raisins, '_Quantity:0')
|
||||
>>> getattr(raisins, '_Quantity#0')
|
||||
10
|
||||
>>> getattr(raisins, '_Quantity:1')
|
||||
>>> getattr(raisins, '_Quantity#1')
|
||||
6.95
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.price # doctest: +ELLIPSIS
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<model_v4c.Quantity object at 0x...>
|
||||
>>> br_nuts = LineItem('Brazil nuts', 10, 34.95)
|
||||
>>> br_nuts.price
|
||||
34.95
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Quantity#0'
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
@ -29,29 +29,33 @@ instance::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
||||
['_NonBlank:0', '_Quantity:0', '_Quantity:1', '__class__', ...
|
||||
['_NonBlank#0', '_Quantity#0', '_Quantity#1', '__class__', ...
|
||||
'description', 'price', 'subtotal', 'weight']
|
||||
>>> getattr(raisins, '_Quantity:0')
|
||||
>>> getattr(raisins, '_Quantity#0')
|
||||
10
|
||||
>>> getattr(raisins, '_NonBlank:0')
|
||||
>>> getattr(raisins, '_NonBlank#0')
|
||||
'Golden raisins'
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.price # doctest: +ELLIPSIS
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<model_v5.Quantity object at 0x...>
|
||||
>>> br_nuts = LineItem('Brazil nuts', 10, 34.95)
|
||||
>>> br_nuts.price
|
||||
34.95
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Quantity#0'
|
||||
|
||||
The `NonBlank` descriptor prevents empty or blank strings to be used
|
||||
for the description:
|
||||
|
||||
>>> br_nuts = LineItem('Brazil Nuts', 10, 34.95)
|
||||
>>> br_nuts.description = ' '
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
>>> void = LineItem('', 1, 1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
|
||||
|
||||
"""
|
||||
|
85
descriptors/bulkfood_v5_check.py
Normal file
85
descriptors/bulkfood_v5_check.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""
|
||||
|
||||
A line item for a bulk food order has description, weight and price fields::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> raisins.weight, raisins.description, raisins.price
|
||||
(10, 'Golden raisins', 6.95)
|
||||
|
||||
A ``subtotal`` method gives the total price for that line item::
|
||||
|
||||
>>> raisins.subtotal()
|
||||
69.5
|
||||
|
||||
The weight of a ``LineItem`` must be greater than 0::
|
||||
|
||||
>>> raisins.weight = -20
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value must be > 0; -20 is not valid.
|
||||
|
||||
No change was made::
|
||||
|
||||
>>> raisins.weight
|
||||
10
|
||||
|
||||
The value of the attributes managed by the descriptors are stored in
|
||||
alternate attributes, created by the descriptors in each ``LineItem``
|
||||
instance::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
||||
['_Check#0', '_Check#1', '_Check#2', '__class__', ...
|
||||
'description', 'price', 'subtotal', 'weight']
|
||||
>>> [getattr(raisins, name) for name in dir(raisins) if name.startswith('_Check#')]
|
||||
['Golden raisins', 10, 6.95]
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<model_v5_check.Check object at 0x...>
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Check#1'
|
||||
|
||||
The `NonBlank` descriptor prevents empty or blank strings to be used
|
||||
for the description:
|
||||
|
||||
>>> br_nuts = LineItem('Brazil Nuts', 10, 34.95)
|
||||
>>> br_nuts.description = ' '
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: ' ' is not valid.
|
||||
>>> void = LineItem('', 1, 1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: '' is not valid.
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
import model_v5_check as model
|
||||
|
||||
def gt_zero(x):
|
||||
'''value must be > 0'''
|
||||
return x if x > 0 else model.INVALID
|
||||
|
||||
def non_blank(txt):
|
||||
txt = txt.strip()
|
||||
return txt if txt else model.INVALID
|
||||
|
||||
|
||||
class LineItem:
|
||||
description = model.Check(non_blank)
|
||||
weight = model.Check(gt_zero)
|
||||
price = model.Check(gt_zero)
|
||||
|
||||
def __init__(self, description, weight, price):
|
||||
self.description = description
|
||||
self.weight = weight
|
||||
self.price = price
|
||||
|
||||
def subtotal(self):
|
||||
return self.weight * self.price
|
||||
|
@ -16,7 +16,7 @@ The weight of a ``LineItem`` must be greater than 0::
|
||||
>>> raisins.weight = -20
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value must be > 0; -20 is not valid.
|
||||
ValueError: value must be > 0
|
||||
|
||||
No change was made::
|
||||
|
||||
@ -27,49 +27,52 @@ The value of the attributes managed by the descriptors are stored in
|
||||
alternate attributes, created by the descriptors in each ``LineItem``
|
||||
instance::
|
||||
|
||||
# BEGIN LINEITEM_V6_DEMO
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
||||
['_Check:0', '_Check:1', '_Check:2', '__class__', ...
|
||||
'description', 'price', 'subtotal', 'weight']
|
||||
>>> [getattr(raisins, name) for name in dir(raisins) if name.startswith('_Check:')]
|
||||
['Golden raisins', 10, 6.95]
|
||||
>>> dir(raisins)[:3]
|
||||
['_NonBlank#description', '_Quantity#price', '_Quantity#weight']
|
||||
>>> LineItem.description.storage_name
|
||||
'_NonBlank#description'
|
||||
>>> raisins.description
|
||||
'Golden raisins'
|
||||
>>> getattr(raisins, '_NonBlank#description')
|
||||
'Golden raisins'
|
||||
|
||||
# END LINEITEM_V6_DEMO
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.price # doctest: +ELLIPSIS
|
||||
<model_v6.Check object at 0x...>
|
||||
>>> br_nuts = LineItem('Brazil nuts', 10, 34.95)
|
||||
>>> br_nuts.price
|
||||
34.95
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<model_v6.Quantity object at 0x...>
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Quantity#weight'
|
||||
|
||||
|
||||
The `NonBlank` descriptor prevents empty or blank strings to be used
|
||||
for the description:
|
||||
|
||||
>>> br_nuts = LineItem('Brazil Nuts', 10, 34.95)
|
||||
>>> br_nuts.description = ' '
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: ' ' is not valid.
|
||||
ValueError: value cannot be empty or blank
|
||||
>>> void = LineItem('', 1, 1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
|
||||
|
||||
"""
|
||||
|
||||
# BEGIN LINEITEM_V5
|
||||
import model_v6 as model # <1>
|
||||
|
||||
def gt_zero(x):
|
||||
'''value must be > 0'''
|
||||
return x if x > 0 else model.INVALID
|
||||
|
||||
def non_blank(txt):
|
||||
txt = txt.strip()
|
||||
return txt if txt else model.INVALID
|
||||
|
||||
# BEGIN LINEITEM_V6
|
||||
import model_v6 as model
|
||||
|
||||
@model.entity # <1>
|
||||
class LineItem:
|
||||
description = model.Check(non_blank) # <2>
|
||||
weight = model.Check(gt_zero)
|
||||
price = model.Check(gt_zero)
|
||||
description = model.NonBlank()
|
||||
weight = model.Quantity()
|
||||
price = model.Quantity()
|
||||
|
||||
def __init__(self, description, weight, price):
|
||||
self.description = description
|
||||
@ -78,4 +81,4 @@ class LineItem:
|
||||
|
||||
def subtotal(self):
|
||||
return self.weight * self.price
|
||||
# END LINEITEM_V5
|
||||
# END LINEITEM_V6
|
||||
|
79
descriptors/bulkfood_v7.py
Normal file
79
descriptors/bulkfood_v7.py
Normal file
@ -0,0 +1,79 @@
|
||||
"""
|
||||
|
||||
A line item for a bulk food order has description, weight and price fields::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> raisins.weight, raisins.description, raisins.price
|
||||
(10, 'Golden raisins', 6.95)
|
||||
|
||||
A ``subtotal`` method gives the total price for that line item::
|
||||
|
||||
>>> raisins.subtotal()
|
||||
69.5
|
||||
|
||||
The weight of a ``LineItem`` must be greater than 0::
|
||||
|
||||
>>> raisins.weight = -20
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value must be > 0
|
||||
|
||||
No change was made::
|
||||
|
||||
>>> raisins.weight
|
||||
10
|
||||
|
||||
The value of the attributes managed by the descriptors are stored in
|
||||
alternate attributes, created by the descriptors in each ``LineItem``
|
||||
instance::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins)[:3]
|
||||
['_NonBlank#description', '_Quantity#price', '_Quantity#weight']
|
||||
>>> LineItem.description.storage_name
|
||||
'_NonBlank#description'
|
||||
>>> raisins.description
|
||||
'Golden raisins'
|
||||
>>> getattr(raisins, '_NonBlank#description')
|
||||
'Golden raisins'
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<model_v7.Quantity object at 0x...>
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Quantity#weight'
|
||||
|
||||
|
||||
The `NonBlank` descriptor prevents empty or blank strings to be used
|
||||
for the description:
|
||||
|
||||
>>> br_nuts = LineItem('Brazil Nuts', 10, 34.95)
|
||||
>>> br_nuts.description = ' '
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
>>> void = LineItem('', 1, 1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
|
||||
"""
|
||||
|
||||
# BEGIN LINEITEM_V7
|
||||
import model_v7 as model
|
||||
|
||||
class LineItem(model.Entity): # <1>
|
||||
description = model.NonBlank()
|
||||
weight = model.Quantity()
|
||||
price = model.Quantity()
|
||||
|
||||
def __init__(self, description, weight, price):
|
||||
self.description = description
|
||||
self.weight = weight
|
||||
self.price = price
|
||||
|
||||
def subtotal(self):
|
||||
return self.weight * self.price
|
||||
# END LINEITEM_V7
|
86
descriptors/bulkfood_v8.py
Normal file
86
descriptors/bulkfood_v8.py
Normal file
@ -0,0 +1,86 @@
|
||||
"""
|
||||
|
||||
A line item for a bulk food order has description, weight and price fields::
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> raisins.weight, raisins.description, raisins.price
|
||||
(10, 'Golden raisins', 6.95)
|
||||
|
||||
A ``subtotal`` method gives the total price for that line item::
|
||||
|
||||
>>> raisins.subtotal()
|
||||
69.5
|
||||
|
||||
The weight of a ``LineItem`` must be greater than 0::
|
||||
|
||||
>>> raisins.weight = -20
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value must be > 0
|
||||
|
||||
No change was made::
|
||||
|
||||
>>> raisins.weight
|
||||
10
|
||||
|
||||
>>> raisins = LineItem('Golden raisins', 10, 6.95)
|
||||
>>> dir(raisins)[:3]
|
||||
['_NonBlank#description', '_Quantity#price', '_Quantity#weight']
|
||||
>>> LineItem.description.storage_name
|
||||
'_NonBlank#description'
|
||||
>>> raisins.description
|
||||
'Golden raisins'
|
||||
>>> getattr(raisins, '_NonBlank#description')
|
||||
'Golden raisins'
|
||||
|
||||
If the descriptor is accessed in the class, the descriptor object is
|
||||
returned:
|
||||
|
||||
>>> LineItem.weight # doctest: +ELLIPSIS
|
||||
<model_v8.Quantity object at 0x...>
|
||||
>>> LineItem.weight.storage_name
|
||||
'_Quantity#weight'
|
||||
|
||||
|
||||
The `NonBlank` descriptor prevents empty or blank strings to be used
|
||||
for the description:
|
||||
|
||||
>>> br_nuts = LineItem('Brazil Nuts', 10, 34.95)
|
||||
>>> br_nuts.description = ' '
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
>>> void = LineItem('', 1, 1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: value cannot be empty or blank
|
||||
|
||||
|
||||
Fields can be retrieved in the order they were declared:
|
||||
|
||||
# BEGIN LINEITEM_V8_DEMO
|
||||
>>> for name in LineItem.field_names():
|
||||
... print(name)
|
||||
...
|
||||
description
|
||||
weight
|
||||
price
|
||||
|
||||
# END LINEITEM_V8_DEMO
|
||||
|
||||
"""
|
||||
|
||||
import model_v8 as model
|
||||
|
||||
class LineItem(model.Entity):
|
||||
description = model.NonBlank()
|
||||
weight = model.Quantity()
|
||||
price = model.Quantity()
|
||||
|
||||
def __init__(self, description, weight, price):
|
||||
self.description = description
|
||||
self.weight = weight
|
||||
self.price = price
|
||||
|
||||
def subtotal(self):
|
||||
return self.weight * self.price
|
@ -6,7 +6,7 @@ class Quantity:
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}:{}'.format(prefix, index)
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
|
@ -9,7 +9,7 @@ class AutoStorage: # <1>
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}:{}'.format(prefix, index)
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
|
52
descriptors/model_v5_check.py
Normal file
52
descriptors/model_v5_check.py
Normal file
@ -0,0 +1,52 @@
|
||||
import abc
|
||||
|
||||
|
||||
class AutoStorage:
|
||||
__counter = 0
|
||||
|
||||
def __init__(self):
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
if instance is None:
|
||||
return self
|
||||
else:
|
||||
return getattr(instance, self.storage_name)
|
||||
|
||||
def __set__(self, instance, value):
|
||||
setattr(instance, self.storage_name, value)
|
||||
|
||||
|
||||
class Validated(abc.ABC, AutoStorage):
|
||||
|
||||
def __set__(self, instance, value):
|
||||
value = self.validate(instance, value)
|
||||
super().__set__(instance, value)
|
||||
|
||||
@abc.abstractmethod
|
||||
def validate(self, instance, value):
|
||||
"""return validated value or raise ValueError"""
|
||||
|
||||
INVALID = object()
|
||||
|
||||
class Check(Validated):
|
||||
|
||||
def __init__(self, checker):
|
||||
super().__init__()
|
||||
self.checker = checker
|
||||
if checker.__doc__ is None:
|
||||
doc = ''
|
||||
else:
|
||||
doc = checker.__doc__ + '; '
|
||||
self.message = doc + '{!r} is not valid.'
|
||||
|
||||
|
||||
def validate(self, instance, value):
|
||||
result = self.checker(value)
|
||||
if result is INVALID:
|
||||
raise ValueError(self.message.format(value))
|
||||
return result
|
@ -1,15 +1,14 @@
|
||||
# BEGIN MODEL_V5
|
||||
import abc
|
||||
|
||||
|
||||
class AutoStorage: # <1>
|
||||
class AutoStorage:
|
||||
__counter = 0
|
||||
|
||||
def __init__(self):
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}:{}'.format(prefix, index)
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
@ -19,41 +18,22 @@ class AutoStorage: # <1>
|
||||
return getattr(instance, self.storage_name)
|
||||
|
||||
def __set__(self, instance, value):
|
||||
setattr(instance, self.storage_name, value) # <2>
|
||||
setattr(instance, self.storage_name, value)
|
||||
|
||||
|
||||
class Validated(abc.ABC, AutoStorage): # <3>
|
||||
class Validated(abc.ABC, AutoStorage):
|
||||
|
||||
def __set__(self, instance, value):
|
||||
value = self.validate(instance, value) # <4>
|
||||
super().__set__(instance, value) # <5>
|
||||
value = self.validate(instance, value)
|
||||
super().__set__(instance, value)
|
||||
|
||||
@abc.abstractmethod
|
||||
def validate(self, instance, value): # <6>
|
||||
def validate(self, instance, value):
|
||||
"""return validated value or raise ValueError"""
|
||||
|
||||
INVALID = object()
|
||||
|
||||
class Check(Validated):
|
||||
|
||||
def __init__(self, checker):
|
||||
super().__init__()
|
||||
self.checker = checker
|
||||
if checker.__doc__ is None:
|
||||
doc = ''
|
||||
else:
|
||||
doc = checker.__doc__ + '; '
|
||||
self.message = doc + '{!r} is not valid.'
|
||||
|
||||
|
||||
def validate(self, instance, value):
|
||||
result = self.checker(value)
|
||||
if result is INVALID:
|
||||
raise ValueError(self.message.format(value))
|
||||
return result
|
||||
|
||||
|
||||
class Quantity(Validated): # <7>
|
||||
class Quantity(Validated):
|
||||
"""a number greater than zero"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
if value <= 0:
|
||||
@ -62,11 +42,19 @@ class Quantity(Validated): # <7>
|
||||
|
||||
|
||||
class NonBlank(Validated):
|
||||
"""a string with at least one non-space character"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
value = value.strip()
|
||||
if len(value) == 0:
|
||||
raise ValueError('value cannot be empty or blank')
|
||||
return value # <8>
|
||||
return value
|
||||
|
||||
# END MODEL_V5
|
||||
# BEGIN MODEL_V6
|
||||
def entity(cls): # <1>
|
||||
for key, attr in cls.__dict__.items(): # <2>
|
||||
if isinstance(attr, Validated): # <3>
|
||||
type_name = type(attr).__name__
|
||||
attr.storage_name = '_{}#{}'.format(type_name, key) # <4>
|
||||
return cls # <5>
|
||||
# END MODEL_V6
|
||||
|
66
descriptors/model_v7.py
Normal file
66
descriptors/model_v7.py
Normal file
@ -0,0 +1,66 @@
|
||||
import abc
|
||||
|
||||
|
||||
class AutoStorage:
|
||||
__counter = 0
|
||||
|
||||
def __init__(self):
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
if instance is None:
|
||||
return self
|
||||
else:
|
||||
return getattr(instance, self.storage_name)
|
||||
|
||||
def __set__(self, instance, value):
|
||||
setattr(instance, self.storage_name, value)
|
||||
|
||||
|
||||
class Validated(abc.ABC, AutoStorage):
|
||||
|
||||
def __set__(self, instance, value):
|
||||
value = self.validate(instance, value)
|
||||
super().__set__(instance, value)
|
||||
|
||||
@abc.abstractmethod
|
||||
def validate(self, instance, value):
|
||||
"""return validated value or raise ValueError"""
|
||||
|
||||
|
||||
class Quantity(Validated):
|
||||
"""a number greater than zero"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
if value <= 0:
|
||||
raise ValueError('value must be > 0')
|
||||
return value
|
||||
|
||||
|
||||
class NonBlank(Validated):
|
||||
"""a string with at least one non-space character"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
value = value.strip()
|
||||
if len(value) == 0:
|
||||
raise ValueError('value cannot be empty or blank')
|
||||
return value
|
||||
|
||||
# BEGIN MODEL_V7
|
||||
class EntityMeta(type):
|
||||
"""Metaclass for business entities with validated fields"""
|
||||
|
||||
def __init__(self, name, bases, attr_dict):
|
||||
super().__init__(name, bases, attr_dict) # <1>
|
||||
for key, attr in attr_dict.items(): # <2>
|
||||
if isinstance(attr, Validated):
|
||||
type_name = type(attr).__name__
|
||||
attr.storage_name = '_{}#{}'.format(type_name, key)
|
||||
|
||||
class Entity(metaclass=EntityMeta): # <3>
|
||||
"""Business entity with validated fields"""
|
||||
# END MODEL_V7
|
80
descriptors/model_v8.py
Normal file
80
descriptors/model_v8.py
Normal file
@ -0,0 +1,80 @@
|
||||
import abc
|
||||
import collections
|
||||
|
||||
|
||||
class AutoStorage:
|
||||
__counter = 0
|
||||
|
||||
def __init__(self):
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
if instance is None:
|
||||
return self
|
||||
else:
|
||||
return getattr(instance, self.storage_name)
|
||||
|
||||
def __set__(self, instance, value):
|
||||
setattr(instance, self.storage_name, value)
|
||||
|
||||
|
||||
class Validated(abc.ABC, AutoStorage):
|
||||
|
||||
def __set__(self, instance, value):
|
||||
value = self.validate(instance, value)
|
||||
super().__set__(instance, value)
|
||||
|
||||
@abc.abstractmethod
|
||||
def validate(self, instance, value):
|
||||
"""return validated value or raise ValueError"""
|
||||
|
||||
|
||||
class Quantity(Validated):
|
||||
"""a number greater than zero"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
if value <= 0:
|
||||
raise ValueError('value must be > 0')
|
||||
return value
|
||||
|
||||
|
||||
class NonBlank(Validated):
|
||||
"""a string with at least one non-space character"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
value = value.strip()
|
||||
if len(value) == 0:
|
||||
raise ValueError('value cannot be empty or blank')
|
||||
return value
|
||||
|
||||
# BEGIN MODEL_V8
|
||||
class EntityMeta(type):
|
||||
"""Metaclass for business entities with validated fields"""
|
||||
|
||||
@classmethod
|
||||
def __prepare__(cls, name, bases):
|
||||
return collections.OrderedDict() # <1>
|
||||
|
||||
def __init__(self, name, bases, attr_dict):
|
||||
super().__init__(name, bases, attr_dict)
|
||||
self._field_names = [] # <2>
|
||||
for key, attr in attr_dict.items(): # <3>
|
||||
if isinstance(attr, Validated):
|
||||
type_name = type(attr).__name__
|
||||
attr.storage_name = '_{}#{}'.format(type_name, key)
|
||||
self._field_names.append(key) # <4>
|
||||
|
||||
|
||||
class Entity(metaclass=EntityMeta):
|
||||
"""Business entity with validated fields"""
|
||||
|
||||
@classmethod
|
||||
def field_names(cls): # <5>
|
||||
for name in cls._field_names:
|
||||
yield name
|
||||
|
||||
# END MODEL_V8
|
Loading…
x
Reference in New Issue
Block a user