Skip to content

Instantly share code, notes, and snippets.

@andymitchhank
Last active June 5, 2018 21:22
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 andymitchhank/7677786e1d49eda7f6b70002e74915f7 to your computer and use it in GitHub Desktop.
Save andymitchhank/7677786e1d49eda7f6b70002e74915f7 to your computer and use it in GitHub Desktop.
from typing import Any, Dict, NamedTuple, Type
class MyTuple(NamedTuple):
""" Sample tuple class """
name: str
desc: str
def coerce_to_namedtuple(d: Dict[str, Any], T: Type):
""" Create a NamedTuple from a dict, ignoring extra keys in the dict """
return T(**{k: v for k, v in d.items() if k in T._fields})
d = dict(name='Some Name', desc='Some Description', other='Anything Else')
print(coerce_to_namedtuple(d, MyTuple))
# output: MyTuple(name='Some Name', desc='Some Description')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment