update from atlas

This commit is contained in:
Luciano Ramalho
2015-03-31 16:53:46 -03:00
parent 290079ec9a
commit 104b2c9d2d
24 changed files with 674 additions and 205 deletions

View File

@@ -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>

View File

@@ -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):

View File

@@ -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'
"""

View File

@@ -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
"""

View 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

View File

@@ -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

View 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

View 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

View File

@@ -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):

View File

@@ -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):

View 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

View File

@@ -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
View 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
View 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