Python typing.TypedDict() Examples

The following are 3 code examples of typing.TypedDict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: _typing.py    From pytablewriter with MIT License 6 votes vote down vote up
def _typeddict_new(cls, _typename, _fields=None, **kwargs):
        total = kwargs.pop('total', True)
        if _fields is None:
            _fields = kwargs
        elif kwargs:
            raise TypeError("TypedDict takes either a dict or keyword arguments,"
                            " but not both")

        ns = {'__annotations__': dict(_fields), '__total__': total}
        try:
            # Setting correct module is necessary to make typed dict classes pickleable.
            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
        except (AttributeError, ValueError):
            pass

        return _TypedDictMeta(_typename, (), ns) 
Example #2
Source File: _typing.py    From pytablewriter with MIT License 6 votes vote down vote up
def __new__(cls, name, bases, ns, total=True):
            # Create new typed dict class object.
            # This method is called directly when TypedDict is subclassed,
            # or via _typeddict_new when TypedDict is instantiated. This way
            # TypedDict supports all three syntaxes described in its docstring.
            # Subclasses and instances of TypedDict return actual dictionaries
            # via _dict_new.
            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
            tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)

            anns = ns.get('__annotations__', {})
            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
            anns = {n: typing._type_check(tp, msg) for n, tp in anns.items()}
            for base in bases:
                anns.update(base.__dict__.get('__annotations__', {}))
            tp_dict.__annotations__ = anns
            if not hasattr(tp_dict, '__total__'):
                tp_dict.__total__ = total
            return tp_dict 
Example #3
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def _check_fails(cls, other):
        try:
            if sys._getframe(1).f_globals['__name__'] not in ['abc',
                                                              'functools',
                                                              'typing']:
                # Typed dicts are only for static structural subtyping.
                raise TypeError('TypedDict does not support instance and class checks')
        except (AttributeError, ValueError):
            pass
        return False