Skip to content

Instantly share code, notes, and snippets.

@vst
Created December 29, 2015 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vst/abe731e2475c1400126d to your computer and use it in GitHub Desktop.
Save vst/abe731e2475c1400126d to your computer and use it in GitHub Desktop.
"""
Provides a cast operations module.
>>> cast_to_decimal(1.0001)
Decimal('1.0001')
>>> cast_to_decimal(1)
Decimal('1')
>>> cast_to_decimal("1.0001")
Decimal('1.0001')
>>> cast_to_decimal(Decimal("1.0001"))
Decimal('1.0001')
>>> cast_to_date("2015-01-01")
date(2015, 1, 1)
>>> cast_to_date(datetime.now()) == date.today()
True
>>> cast_to_date(date(2015, 1, 1))
date(2015, 1, 1)
"""
from decimal import Decimal
from datetime import date, datetime
from multimethod import multidispatch
@multidispatch
def cast_to_decimal(arg):
"""
Casts the given argument to Decimal, if possible. Raises ValueError
if argument is not recognized as compatible.
:param arg: The argument to be cast to Decimal.
:return: A Decimal or raises a ValueError
"""
raise ValueError("{} can not be cast to Decimal".format(repr(arg)))
@cast_to_decimal.register(float)
def _(arg):
return Decimal(str(arg))
@cast_to_decimal.register(int)
def _(arg):
return Decimal(arg)
@cast_to_decimal.register(str)
def _(arg):
return Decimal(arg)
@cast_to_decimal.register(Decimal)
def _(arg):
return arg
@multidispatch
def cast_to_date(arg):
"""
Casts the given argument to date, if possible. Raises ValueError
if argument is not recognized as compatible.
:param arg: The argument to be cast to date.
:return: A date or raises a ValueError
"""
raise ValueError("{} can not be cast to date".format(repr(arg)))
@cast_to_date.register(str)
def _(arg):
return datetime.strptime(arg, "%Y-%m-%s")
@cast_to_date.register(datetime)
def _(arg):
return datetime.date()
@cast_to_date.register(date)
def _(arg):
return arg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment