Skip to content

Instantly share code, notes, and snippets.

@alanbriolat
Created August 3, 2017 08:56
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 alanbriolat/2730b2b78ec9f058f2242a1dc492bc99 to your computer and use it in GitHub Desktop.
Save alanbriolat/2730b2b78ec9f058f2242a1dc492bc99 to your computer and use it in GitHub Desktop.
namedtuple with type casts
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