Skip to content

Instantly share code, notes, and snippets.

@cefn
Created June 28, 2018 11:01
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 cefn/629a8de59666debc357f4e88198092ed to your computer and use it in GitHub Desktop.
Save cefn/629a8de59666debc357f4e88198092ed to your computer and use it in GitHub Desktop.
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