Skip to content

Instantly share code, notes, and snippets.

@jrjames83
Last active December 28, 2016 03:41
Show Gist options
  • Save jrjames83/2c65f049d12b6badf3aeb3cf99025240 to your computer and use it in GitHub Desktop.
Save jrjames83/2c65f049d12b6badf3aeb3cf99025240 to your computer and use it in GitHub Desktop.
Example of a function + lambda to enforce type checking on attr init and settr operations
def typed_property(name, expected_type):
private_name = '_' + name
@property
def prop(self):
return getattr(self, private_name)
@prop.setter
def prop(self, value):
if not isinstance(value, expected_type):
raise TypeError('Expected {}'.format(expected_type))
setattr(self, private_name, value)
return prop
Integer = lambda name: typed_property(name, int)
Float = lambda name: typed_property(name, float)
String = lambda name: typed_property(name, str)
class Holding(object):
shares = Integer('shares')
name = String('name')
price = Float('price')
#without the lambda's
# shares = typed_property('shares', int)
# name = typed_property('name', str)
# price = typed_property('price', float)
def __init__(self, name, price, shares):
self.name = name
self.price = price
self.shares = shares
#Long winded approach
# @property
# def shares(self):
# return self._shares
#
# @shares.setter
# def shares(self, newshares):
# if not isinstance(newshares, int):
# raise TypeError('Expected a Float')
# if newshares < 0:
# raise ValueError('Must be > 0')
# self._shares = newshares
#
# @property
# def price(self):
# return self._price
#
# @price.setter
# def price(self, newprice):
# if not isinstance(newprice, float):
# raise TypeError('Expected a Float')
# if newprice < 0:
# raise ValueError('Must be > 0')
# self._price = newprice
@property #avoid having to invoke function
def value(self):
return self.price * self.shares
def __repr__(self):
return "{!r} {!r} {!r}".format(self.name, self.price, self.shares)
def __str__(self):
return "{!r} {!r} {!r}".format(self.name, self.price, self.shares)
x = Holding('AAPL', 300.00, 100)
print(x)
print(x.value) #not require the invocation now due to property
x.price = '234' #Float required
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment