Created
June 28, 2018 11:01
-
-
Save cefn/629a8de59666debc357f4e88198092ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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