Created
August 3, 2017 08:56
-
-
Save alanbriolat/2730b2b78ec9f058f2242a1dc492bc99 to your computer and use it in GitHub Desktop.
namedtuple with type casts
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
from collections import namedtuple | |
def nocast(x): | |
return x | |
def crazytuple(name, fields, casts): | |
_tuple = namedtuple(name, fields) | |
class _casting_tuple(_tuple): | |
def __new__(cls, *args, **kwargs): | |
args = [casts.get(f, nocast)(v) for f, v in zip(cls._fields, args)] | |
kwargs = {f: casts.get(f, nocast)(v) for f, v in kwargs.items()} | |
return super(_casting_tuple, cls).__new__(cls, *args, **kwargs) | |
return _casting_tuple | |
Foo = crazytuple('Foo', ['a', 'b'], {'b': float}) | |
print(Foo(1, 2)) | |
# Foo(a=1, b=2.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment