Skip to content

Instantly share code, notes, and snippets.

@richmondwang
Last active August 16, 2016 14:36
Show Gist options
  • Save richmondwang/b68911cd744ac12e96e2df2793364181 to your computer and use it in GitHub Desktop.
Save richmondwang/b68911cd744ac12e96e2df2793364181 to your computer and use it in GitHub Desktop.
Converts string or int to valid Month.
class Month(object):
"""Validates a string as a Month of a year
Args:
return_type (int): NUMBER = 0, WORD = 1, FULL = 2
msg (str): the message when it fails
"""
NUMBER = 0
WORD = 1
FULL = 2
__months_num = range(1, 13)
__months_full = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
__months_word = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
def __init__(self, return_type=FULL, msg='Not a valid Month value.'):
self.type = return_type
self.msg = msg
def __call__(self, v):
if isinstance(v, basestring):
if v.title() in self.__months_full:
index = self.__months_full.index(v.title())
elif v.title() in self.__months_word:
index = self.__months_word.index(v.title())
else:
raise Exception(self.msg)
elif isinstance(v, int):
if v not in self.__months_num:
raise Exception(self.msg)
index = self.__months_num.index(v)
else:
raise Exception(self.msg)
if self.type is self.NUMBER:
base = self.__months_num
elif self.type is self.WORD:
base = self.__months_word
else:
base = self.__months_full
return base[index]
def __repr__(self):
if self.type is self.NUMBER:
_type = 'NUMBER'
elif self.type is self.WORD:
_type = 'WORD'
else:
_type = 'FULL'
return 'Month(%s)' % _type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment