Last active
June 5, 2018 21:22
-
-
Save andymitchhank/7677786e1d49eda7f6b70002e74915f7 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
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