Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
def mapInitArgs(cls, fromType, toType, translateFun):
oldinit = cls.__init__
def newinit(self, *args, **kwargs):
fields = cls.__dataclass_fields__
fieldIter = iter(fields)
for pos,arg in enumerate(args):
fieldName = next(fieldIter)
if fields[fieldName].type is toType and type(arg) is fromType:
args[pos] = translateFun(arg)
for fieldName in fieldIter:
if fields[fieldName].type is toType and fieldName in kwargs:
kwarg = kwargs[fieldName]
if type(kwarg) is fromType:
kwargs[fieldName] = translateFun(kwarg)
return oldinit(self, *args, **kwargs)
cls.__init__ = newinit
mapInitArgs(SchoolTerm, str, datetime.datetime, dateutil.parser)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.