A simple mixin for create Value Objects
Project description
Based on Ruby Gem by NoFlopSquad (https://github.com/noflopsquad/value-object)
Installation
> pip install simple-value-object
Usage
Constructor and field readers
from simple_value_object import ValueObject
class Point(ValueObject):
def __init__(self, x, y):
pass
point = Point(1, 2)
point.x
# 1
point.y
# 2
point.x = 5
# CannotBeChangeException: You cannot change values from a Value Object, create a new one
class Date(ValueObject):
def __init__(self, day, month, year):
pass
date = Date(1, 10, 2015)
date.day
# 1
date.month
# 10
date.year
# 2015
date.month = 5
# CannotBeChangeException: You cannot change values from a Value Object, create a new one
Equality based on field values
from simple_value_object import ValueObject
class Point(ValueObject):
def __init__(self, x, y):
pass
a_point = Point(5, 3)
same_point = Point(5, 3)
a_point == same_point
# True
a_different_point = Point(6, 3)
a_point == a_different_point
# False
Hash code based on field values
from simple_value_object import ValueObject
class Point(ValueObject):
def __init__(self, x, y):
pass
a_point = Point(5, 3)
same_point = Point(5, 3)
a_point.hash == same_point.hash
# True
a_different_point = Point.new(6, 3)
a_point.hash == a_different_point.hash
# False
Invariants
from simple_value_object import ValueObject, invariant
class Point(ValueObject):
def __init__(self, x, y):
pass
@invariant
def inside_first_quadrant(cls, instance):
return instance.x > 0 and instance.y > 0
@invariant
def x_less_than_y(cls, instance):
return instance.x < instance.y
Point(-5, 3)
#ViolatedInvariantException: Args values [-5, 3] violates invariant: inside_first_cuadrant
Point(6, 3)
#ViolatedInvariantException: Args values [6, 3] violates invariant: x_less_than_y
Point(1,3)
#<__main__.Point at 0x7f2bd043c780>
Test
> pip install -r requirements-test.txt
> PYTHONPATH=$PYTHONPATH:. mamba
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for simple-value-object-0.2.5.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 46e72eb15e7b54ad6c0d641c7798cb9cffcc9af886733a15451d64e15131dd61 |
|
MD5 | a57830716aa47e7193eda36c9a6c4ffb |
|
BLAKE2b-256 | f5a6836d530498ed373b8fb31c58faae3f368a7f666365a02120f93c323d5354 |
Close
Hashes for simple_value_object-0.2.5-py2-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 43db3c089f88d4c55b0b84162eb8cd2c1f29008b554abb267dfd8fe0099c8e22 |
|
MD5 | 568074e690575373e42b7bfd54ac989a |
|
BLAKE2b-256 | 8a50913854a66234cf579f5046a19cf057c10f509a08c1ac29d293557b2e4044 |