Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonsch...
[]
Please provide a description of the function:def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
[]
Please provide a description of the function:def create(from_records, to_records, index_columns, ignore_columns=None): from_indexed = records.index(from_records, index_columns) to_indexed = records.index(to_records, index_columns) if ignore_columns is not None: from_indexed = records.filter_ig...
[ "\n Diff two sets of records, using the index columns as the primary key for\n both datasets.\n " ]
Please provide a description of the function:def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
[]
Please provide a description of the function:def record_diff(lhs, rhs): "Diff an individual row." delta = {} for k in set(lhs).union(rhs): from_ = lhs[k] to_ = rhs[k] if from_ != to_: delta[k] = {'from': from_, 'to': to_} return delta
[]
Please provide a description of the function:def filter_significance(diff, significance): changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'fields': {k: v for k, v in delta['fields'].items() ...
[ "\n Prune any changes in the patch which are due to numeric changes less than this level of\n significance.\n " ]
Please provide a description of the function:def _is_significant(change, significance): try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
[ "\n Return True if a change is genuinely significant given our tolerance.\n " ]
Please provide a description of the function:def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, sep=sep) to_records = records.load(to_str...
[ "\n Diff two CSV files, returning the patch which transforms one into the\n other.\n " ]
Please provide a description of the function:def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO, strict: bool = True, sep: str = ','): diff = patch.load(patch_stream) from_records = records.load(fromcsv_stream, sep=sep) to_records = patch.apply(diff, from_...
[ "\n Apply the patch to the source CSV file, and save the result to the target\n file.\n " ]
Please provide a description of the function:def patch_records(diff, from_records, strict=True): return patch.apply(diff, from_records, strict=strict)
[ "\n Apply the patch to the sequence of records, returning the transformed\n records.\n " ]
Please provide a description of the function:def _nice_fieldnames(all_columns, index_columns): "Indexes on the left, other fields in alphabetical order on the right." non_index_columns = set(all_columns).difference(index_columns) return index_columns + sorted(non_index_columns)
[]
Please provide a description of the function:def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None, sep=',', quiet=False, ignore_columns=None, significance=None): if ignore_columns is not None: for i in ignore_columns: if i in index_columns: ...
[ "\n Compare two csv files to see what rows differ between them. The files\n are each expected to have a header row, and for each row to be uniquely\n identified by one or more indexing columns.\n " ]
Please provide a description of the function:def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_csv, sep=sep) diff = pat...
[ "\n Print a summary of the difference between the two files.\n " ]
Please provide a description of the function:def csvpatch_cmd(input_csv, input=None, output=None, strict=True): patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is None else open...
[ "\n Apply the changes from a csvdiff patch to an existing CSV file.\n " ]
Please provide a description of the function:def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
[]
Please provide a description of the function:def _record_key(record: Record) -> List[Tuple[Column, str]]: "An orderable representation of this record." return sorted(record.items())
[]
Please provide a description of the function:def _outter_split(inpt, delim, openers, closers=None, opener_lookup=None): if closers is None: closers = openers if opener_lookup is None: opener_lookup = {} for i in range(len(openers)): opener_lookup[openers[i]] = i stac...
[ "Splits only at delims that are at outter-most level regarding\n openers/closers pairs.\n Unchecked requirements:\n Only supports length-1 delim, openers and closers.\n delim must not be member of openers or closers.\n len(openers) == len(closers) or closers == None\n " ]
Please provide a description of the function:def getargspecs(func): if func is None: raise TypeError('None is not a Python function') if hasattr(func, 'ch_func'): return getargspecs(func.ch_func) elif hasattr(func, 'ov_func'): return getargspecs(func.ov_func) if hasattr(insp...
[ "Bridges inspect.getargspec and inspect.getfullargspec.\n Automatically selects the proper one depending of current Python version.\n Automatically bypasses wrappers from typechecked- and override-decorators.\n " ]
Please provide a description of the function:def get_required_kwonly_args(argspecs): try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly res = [] for name in kwonly: if not name in argspecs.kwonlydefaults: r...
[ "Determines whether given argspecs implies required keywords-only args\n and returns them as a list. Returns empty list if no such args exist.\n " ]
Please provide a description of the function:def getargnames(argspecs, with_unbox=False): # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: kw = argspecs.keywords except AttributeError: kw = argspecs.varkw try: ...
[ "Resembles list of arg-names as would be seen in a function signature, including\n var-args, var-keywords and keyword-only args.\n " ]
Please provide a description of the function:def fromargskw(argskw, argspecs, slf_or_clsm = False): res_args = argskw try: kwds = argspecs.keywords except AttributeError: kwds = argspecs.varkw if not kwds is None: res_kw = argskw[-1] res_args = argskw[:-1] else: ...
[ "Turns a linearized list of args into (args, keywords) form\n according to given argspecs (like inspect module provides).\n " ]
Please provide a description of the function:def get_staticmethod_qualname(staticmeth): func = _actualfunc(staticmeth) module = sys.modules[func.__module__] nst = _get_class_nesting_list_for_staticmethod(staticmeth, module, [], set()) nst = [cl.__name__ for cl in nst] return '.'.join(nst)+'.'+f...
[ "Determines the fully qualified name of a static method.\n Yields a result similar to what __qualname__ would contain, but is applicable\n to static methods and also works in Python 2.7.\n " ]
Please provide a description of the function:def get_class_qualname(cls): if hasattr(cls, '__qualname__'): return cls.__qualname__ module = sys.modules[cls.__module__] if cls.__module__ == 'typing' and not hasattr(cls, '__name__'): # Python 3.7 return cls._name if hasattr(mo...
[ "Determines the fully qualified name of a class.\n Yields a result similar to what __qualname__ contains, but also works on\n Python 2.7.\n " ]
Please provide a description of the function:def search_class_module(cls, deep_search=True): for md_name in sys.modules: module = sys.modules[md_name] if hasattr(module, cls.__name__) and getattr(module, cls.__name__) is cls: return module if deep_search: for md_name in ...
[ "E.g. if cls is a TypeVar, cls.__module__ won't contain the actual module\n that declares cls. This returns the actual module declaring cls.\n Can be used with any class (not only TypeVar), though usually cls.__module__\n is the recommended way.\n If deep_search is True (default) this even finds the cor...
Please provide a description of the function:def get_class_that_defined_method(meth): if is_classmethod(meth): return meth.__self__ if hasattr(meth, 'im_class'): return meth.im_class elif hasattr(meth, '__qualname__'): # Python 3 try: cls_names = meth.__qualn...
[ "Determines the class owning the given method.\n " ]
Please provide a description of the function:def is_method(func): func0 = _actualfunc(func) argNames = getargnames(getargspecs(func0)) if len(argNames) > 0: if argNames[0] == 'self': if inspect.ismethod(func): return True elif sys.version_info.major >= 3:...
[ "Detects if the given callable is a method. In context of pytypes this\n function is more reliable than plain inspect.ismethod, e.g. it automatically\n bypasses wrappers from typechecked and override decorators.\n " ]
Please provide a description of the function:def is_classmethod(meth): if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth.__self__, meth...
[ "Detects if the given callable is a classmethod.\n " ]
Please provide a description of the function:def get_current_args(caller_level = 0, func = None, argNames = None): if argNames is None: argNames = getargnames(getargspecs(func)) if func is None: func = get_current_function(caller_level+1) if isinstance(func, property): func = fu...
[ "Determines the args of current function call.\n Use caller_level > 0 to get args of even earlier function calls in current stack.\n " ]
Please provide a description of the function:def getmodule(code): try: md = inspect.getmodule(code, code.co_filename) except AttributeError: return inspect.getmodule(code) if md is None: # Jython-specific: # This is currently just a crutch; todo: resolve __pyclasspath__ ...
[ "More robust variant of inspect.getmodule.\n E.g. has less issues on Jython.\n " ]
Please provide a description of the function:def get_callable_fq_for_code(code, locals_dict = None): if code in _code_callable_dict: res = _code_callable_dict[code] if not res[0] is None or locals_dict is None: return res md = getmodule(code) if not md is None: nesti...
[ "Determines the function belonging to a given code object in a fully qualified fashion.\n Returns a tuple consisting of\n - the callable\n - a list of classes and inner classes, locating the callable (like a fully qualified name)\n - a boolean indicating whether the callable is a method\n " ]
Please provide a description of the function:def _calc_traceback_limit(tb): limit = 1 tb2 = tb while not tb2.tb_next is None: try: maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2] except IndexError: maybe_pytypes = None if maybe_p...
[ "Calculates limit-parameter to strip away pytypes' internals when used\n with API from traceback module.\n " ]
Please provide a description of the function:def _pytypes_excepthook(exctype, value, tb): if pytypes.clean_traceback and issubclass(exctype, TypeError): traceback.print_exception(exctype, value, tb, _calc_traceback_limit(tb)) else: if _sys_excepthook is None: sys.__excepthook__(...
[ "\"An excepthook suitable for use as sys.excepthook, that strips away\n the part of the traceback belonging to pytypes' internals.\n Can be switched on and off via pytypes.clean_traceback\n or pytypes.set_clean_traceback.\n The latter automatically installs this hook in sys.excepthook.\n " ]
Please provide a description of the function:def get_generator_type(genr): if genr in _checked_generator_types: return _checked_generator_types[genr] if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals: return genr.gi_frame.f_locals['gen_type'] else: cllble, ne...
[ "Obtains PEP 484 style type of a generator object, i.e. returns a\n typing.Generator object.\n " ]
Please provide a description of the function:def get_iterable_itemtype(obj): # support further specific iterables on demand try: if isinstance(obj, range): tpl = tuple(deep_type(obj.start), deep_type(obj.stop), deep_type(obj.step)) return Union[tpl] except TypeError: ...
[ "Attempts to get an iterable's itemtype without iterating over it,\n not even partly. Note that iterating over an iterable might modify\n its inner state, e.g. if it is an iterator.\n Note that obj is expected to be an iterable, not a typing.Iterable.\n This function leverages various alternative ways t...
Please provide a description of the function:def get_Generic_itemtype(sq, simplify=True): if is_Tuple(sq): if simplify: itm_tps = [x for x in get_Tuple_params(sq)] simplify_for_Union(itm_tps) return Union[tuple(itm_tps)] else: return Union[get_Tup...
[ "Retrieves the item type from a PEP 484 generic or subclass of such.\n sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.\n Consequently this also works with typing.List, typing.Set and typing.Dict.\n Note that for typing.Dict and mapping types in general, the key type is regar...
Please provide a description of the function:def get_Mapping_key_value(mp): try: res = _select_Generic_superclass_parameters(mp, typing.Mapping) except TypeError: res = None if res is None: raise TypeError("Has no key/value types: "+type_str(mp)) else: return tuple(r...
[ "Retrieves the key and value types from a PEP 484 mapping or subclass of such.\n mp must be a (subclass of) typing.Mapping.\n " ]
Please provide a description of the function:def get_Generic_parameters(tp, generic_supertype): try: res = _select_Generic_superclass_parameters(tp, generic_supertype) except TypeError: res = None if res is None: raise TypeError("%s has no proper parameters defined by %s."% ...
[ "tp must be a subclass of generic_supertype.\n Retrieves the type values from tp that correspond to parameters\n defined by generic_supertype.\n\n E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent\n to get_Mapping_key_value(tp) except for the error message.\n\n Note that get_Generic_itemt...
Please provide a description of the function:def get_Tuple_params(tpl): try: return tpl.__tuple_params__ except AttributeError: try: if tpl.__args__ is None: return None # Python 3.6 if tpl.__args__[0] == (): return () ...
[ "Python version independent function to obtain the parameters\n of a typing.Tuple object.\n Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.\n Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.\n " ]
Please provide a description of the function:def is_Tuple_ellipsis(tpl): try: return tpl.__tuple_use_ellipsis__ except AttributeError: try: if tpl.__args__ is None: return False # Python 3.6 if tpl.__args__[-1] is Ellipsis: ...
[ "Python version independent function to check if a typing.Tuple object\n contains an ellipsis." ]
Please provide a description of the function:def get_Callable_args_res(clb): try: return clb.__args__, clb.__result__ except AttributeError: # Python 3.6 return clb.__args__[:-1], clb.__args__[-1]
[ "Python version independent function to obtain the parameters\n of a typing.Callable object. Returns as tuple: args, result.\n Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.\n " ]
Please provide a description of the function:def is_Type(tp): if isinstance(tp, type): return True try: typing._type_check(tp, '') return True except TypeError: return False
[ "Python version independent check if an object is a type.\n For Python 3.7 onwards(?) this is not equivalent to\n ``isinstance(tp, type)`` any more, as that call would return\n ``False`` for PEP 484 types.\n Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1.\n " ]
Please provide a description of the function:def is_Union(tp): if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isinstance(tp, typing.UnionMeta) except AttributeError: return Fa...
[ "Python version independent check if a type is typing.Union.\n Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.\n " ]
Please provide a description of the function:def deep_type(obj, depth = None, max_sample = None, get_type = None): return _deep_type(obj, [], 0, depth, max_sample, get_type)
[ "Tries to construct a type for a given value. In contrast to type(...),\n deep_type does its best to fit structured types from typing as close as\n possible to the given value.\n E.g. deep_type((1, 2, 'a')) will return Tuple[int, int, str] rather than\n just tuple.\n Supports various types from typin...
Please provide a description of the function:def _deep_type(obj, checked, checked_len, depth = None, max_sample = None, get_type = None): if depth is None: depth = pytypes.default_typecheck_depth if max_sample is None: max_sample = pytypes.deep_type_samplesize if -1 != max_sample < 2: ...
[ "checked_len allows to operate with a fake length for checked.\n This is necessary to ensure that each depth level operates based\n on the same checked list subset. Otherwise our recursion detection\n mechanism can fall into false-positives.\n " ]
Please provide a description of the function:def is_builtin_type(tp): return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)
[ "Checks if the given type is a builtin one.\n " ]
Please provide a description of the function:def _tp_relfq_name(tp, tp_name=None, assumed_globals=None, update_assumed_globals=None, implicit_globals=None): # _type: (type, Optional[Union[Set[Union[type, types.ModuleType]], Mapping[Union[type, types.ModuleType], str]]], Optional[bool]) -> str i...
[ "Provides the fully qualified name of a type relative to a set of\n modules and types that is assumed as globally available.\n If assumed_globals is None this always returns the fully qualified name.\n If update_assumed_globals is True, this will return the plain type name,\n but will add the type to as...
Please provide a description of the function:def type_str(tp, assumed_globals=None, update_assumed_globals=None, implicit_globals=None, bound_Generic=None, bound_typevars=None): if assumed_globals is None and update_assumed_globals is None: if implicit_globals is None: implicit_...
[ "Generates a nicely readable string representation of the given type.\n The returned representation is workable as a source code string and would\n reconstruct the given type if handed to eval, provided that globals/locals\n are configured appropriately (e.g. assumes that various types from typing\n hav...
Please provide a description of the function:def get_types(func): return _get_types(func, util.is_classmethod(func), util.is_method(func))
[ "Works like get_type_hints, but returns types as a sequence rather than a\n dictionary. Types are returned in declaration order of the corresponding arguments.\n " ]
Please provide a description of the function:def get_member_types(obj, member_name, prop_getter = False): cls = obj.__class__ member = getattr(cls, member_name) slf = not (isinstance(member, staticmethod) or isinstance(member, classmethod)) clsm = isinstance(member, classmethod) return _get_typ...
[ "Still experimental, incomplete and hardly tested.\n Works like get_types, but is also applicable to descriptors.\n " ]
Please provide a description of the function:def _get_types(func, clsm, slf, clss = None, prop_getter = False, unspecified_type = Any, infer_defaults = None): func0 = util._actualfunc(func, prop_getter) # check consistency regarding special case with 'self'-keyword if not slf: argNa...
[ "Helper for get_types and get_member_types.\n " ]
Please provide a description of the function:def _get_type_hints(func, args = None, res = None, infer_defaults = None): if args is None or res is None: args2, res2 = _get_types(func, util.is_classmethod(func), util.is_method(func), unspecified_type = type(NotImplemented), ...
[ "Helper for get_type_hints.\n " ]
Please provide a description of the function:def resolve_fw_decl(in_type, module_name=None, globs=None, level=0, search_stack_depth=2): '''Resolves forward references in ``in_type``, see https://www.python.org/dev/peps/pep-0484/#forward-references. Note: ``globs`` should be a dictionary conta...
[]
Please provide a description of the function:def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): if is_Generic(subclass): if subclass.__origin__ is None or not issubclass(subclass.__origin__, Map...
[ "Helper for _issubclass, a.k.a pytypes.issubtype.\n This subclass-check treats Mapping-values as covariant.\n " ]
Please provide a description of the function:def _find_Generic_super_origin(subclass, superclass_origin): stack = [subclass] param_map = {} while len(stack) > 0: bs = stack.pop() if is_Generic(bs): if not bs.__origin__ is None and len(bs.__origin__.__parameters__) > 0: ...
[ "Helper for _issubclass_Generic.\n " ]
Please provide a description of the function:def _select_Generic_superclass_parameters(subclass, superclass_origin): subclass = _find_base_with_origin(subclass, superclass_origin) if subclass is None: return None if subclass.__origin__ is superclass_origin: return subclass.__args__ ...
[ "Helper for _issubclass_Generic.\n " ]
Please provide a description of the function:def _issubclass_Generic(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): # this function is partly based on code from typing module 3.5.2.2 if subclass is None: return False ...
[ "Helper for _issubclass, a.k.a pytypes.issubtype.\n " ]
Please provide a description of the function:def _issubclass_Tuple(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): # this function is partly based on code from typing module 3.5.2.2 if subclass in _extra_dict: subclass = ...
[ "Helper for _issubclass, a.k.a pytypes.issubtype.\n " ]
Please provide a description of the function:def _issubclass_Union(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): if not follow_fwd_refs: return _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, ...
[ "Helper for _issubclass, a.k.a pytypes.issubtype.\n " ]
Please provide a description of the function:def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): # this function is partly based on code from typing module 3.5.2.2 super_args = get_Union_params(superclass) ...
[ "Helper for _issubclass_Union.\n " ]
Please provide a description of the function:def _has_base(cls, base): if cls is base: return True elif cls is None: return False try: for bs in cls.__bases__: if _has_base(bs, base): return True except: pass return False
[ "Helper for _issubclass, a.k.a pytypes.issubtype.\n " ]
Please provide a description of the function:def _issubclass(subclass, superclass, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): if bound_typevars is None: bound_typevars = {} if superclass is Any: return Tr...
[ "Access this via ``pytypes.is_subtype``.\n Works like ``issubclass``, but supports PEP 484 style types from ``typing`` module.\n\n subclass : type\n The type to check for being a subtype of ``superclass``.\n\n superclass : type\n The type to check for being a supertype of ``subclass``.\n\n bound_G...
Please provide a description of the function:def _issubclass_2(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): if is_Tuple(superclass): return _issubclass_Tuple(subclass, superclass, bound_Generic, bound_typevars, ...
[ "Helper for _issubclass, a.k.a pytypes.issubtype.\n " ]
Please provide a description of the function:def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None, bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None): if bound_typevars is None: bound_typevars = {} # Special treatment if cls is Iterable[...] if ...
[ "Access this via ``pytypes.is_of_type``.\n Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module.\n\n obj : Any\n The object to check for being an instance of ``cls``.\n\n cls : type\n The type to check for ``obj`` being an instance of.\n\n bound_Generic : Optional[Gen...
Please provide a description of the function:def generator_checker_py3(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): initialized = False sn = None try: while True: a = gen.send(sn) if initialized or...
[ "Builds a typechecking wrapper around a Python 3 style generator object.\n " ]
Please provide a description of the function:def generator_checker_py2(gen, gen_type, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): initialized = False sn = None while True: a = gen.send(sn) if initialized or not a is None: ...
[ "Builds a typechecking wrapper around a Python 2 style generator object.\n " ]
Please provide a description of the function:def annotations_func(func): if not has_type_hints(func): # What about defaults? func.__annotations__ = {} func.__annotations__ = _get_type_hints(func, infer_defaults = False) return func
[ "Works like annotations, but is only applicable to functions,\n methods and properties.\n " ]
Please provide a description of the function:def annotations_class(cls): assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use inspect.getmembers here ...
[ "Works like annotations, but is only applicable to classes.\n " ]
Please provide a description of the function:def annotations_module(md): if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md in pytypes.typechecker._pending_modules: # if import is pending, we ju...
[ "Works like annotations, but is only applicable to modules (by explicit call).\n md must be a module or a module name contained in sys.modules.\n " ]
Please provide a description of the function:def annotations(memb): if _check_as_func(memb): return annotations_func(memb) if isclass(memb): return annotations_class(memb) if ismodule(memb): return annotations_module(memb) if memb in sys.modules or memb in pytypes.typechecke...
[ "Decorator applicable to functions, methods, properties,\n classes or modules (by explicit call).\n If applied on a module, memb must be a module or a module name contained in sys.modules.\n See pytypes.set_global_annotations_decorator to apply this on all modules.\n Methods with type comment will have ...
Please provide a description of the function:def simplify_for_Union(type_list): i = 0 while i < len(type_list): j = 0 while j < i: if _issubclass(type_list[j], type_list[i]): del type_list[j] i -= 1 else: j += 1 ...
[ "Removes types that are subtypes of other elements in the list.\n Does not return a copy, but instead modifies the given list.\n Intended for preprocessing of types to be combined into a typing.Union.\n Subtypecheck is backed by pytypes.is_subtype, so this differs from\n typing.Union's own simplificatio...
Please provide a description of the function:def _preprocess_typecheck(argSig, argspecs, slf_or_clsm = False): # todo: Maybe move also slf-logic here vargs = argspecs.varargs try: kw = argspecs.keywords except AttributeError: kw = argspecs.varkw try: kwonly = argspecs.kw...
[ "From a PEP 484 style type-tuple with types for *varargs and/or **kw\n this returns a type-tuple containing Tuple[tp, ...] and Dict[str, kw-tp]\n instead.\n " ]
Please provide a description of the function:def restore_profiler(): idn = threading.current_thread().ident if not sys.getprofile() is None: warn("restore_profiler: Current profile is not None!") if not idn in _saved_profilers: warn("restore_profiler: No saved profiler for calling threa...
[ "If a typechecking profiler is active, e.g. created by\n pytypes.set_global_typechecked_profiler(), such a profiler\n must be restored whenever a TypeCheckError is caught.\n The call must stem from the thread that raised the error.\n Otherwise the typechecking profiler is implicitly disabled.\n Alter...
Please provide a description of the function:def log_type(args_kw, ret, func, slf=False, prop_getter=False, clss=None, argspecs=None, args_kw_type=None, ret_type = None): if args_kw_type is None: args_kw_type = deep_type(args_kw) if ret_type is None: ret_type = deep_type(ret) ...
[ "Stores information of a function or method call into a cache, so pytypes can\n create a PEP 484 stubfile from this information later on (see dump_cache).\n " ]
Please provide a description of the function:def combine_argtype(observations): assert len(observations) > 0 assert is_Tuple(observations[0]) if len(observations) > 1: prms = [get_Tuple_params(observations[0])] ln = len(prms[0]) for obs in observations[1:]: assert is...
[ "Combines a list of Tuple types into one.\n Basically these are combined element wise into a Union with some\n additional unification effort (e.g. can apply PEP 484 style numeric tower).\n " ]
Please provide a description of the function:def combine_type(observations): assert len(observations) > 0 if len(observations) == 1: return observations[0] else: if simplify: simplify_for_Union(observations) return Union[tuple(observations)]
[ "Combines a list of types into one.\n Basically these are combined into a Union with some\n additional unification effort (e.g. can apply PEP 484 style numeric tower).\n " ]
Please provide a description of the function:def dump_cache(path=None, python2=False, suffix=None): typelogging_enabled_tmp = pytypes.typelogging_enabled pytypes.typelogging_enabled = False if suffix is None: suffix = 'pyi2' if python2 else 'pyi' if path is None: path = pytypes.defa...
[ "Writes cached observations by @typelogged into stubfiles.\n Files will be created in the directory provided as 'path'; overwrites\n existing files without notice.\n Uses 'pyi2' suffix if 'python2' flag is given else 'pyi'. Resulting\n files will be Python 2.7 compilant accordingly.\n " ]
Please provide a description of the function:def get_indentation(func): src_lines = getsourcelines(func)[0] for line in src_lines: if not (line.startswith('@') or line.startswith('def') or line.lstrip().startswith('#')): return line[:len(line) - len(line.lstrip())] return pytypes.de...
[ "Extracts a function's indentation as a string,\n In contrast to an inspect.indentsize based implementation,\n this function preserves tabs if present.\n " ]
Please provide a description of the function:def typelogged_func(func): if not pytypes.typelogging_enabled: return func if hasattr(func, 'do_logging'): func.do_logging = True return func elif hasattr(func, 'do_typecheck'): # actually shouldn't happen return _type...
[ "Works like typelogged, but is only applicable to functions,\n methods and properties.\n " ]
Please provide a description of the function:def typelogged_class(cls): if not pytypes.typelogging_enabled: return cls assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Pyt...
[ "Works like typelogged, but is only applicable to classes.\n " ]
Please provide a description of the function:def typelogged_module(md): if not pytypes.typelogging_enabled: return md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md in pytypes.typechecker._p...
[ "Works like typelogged, but is only applicable to modules by explicit call).\n md must be a module or a module name contained in sys.modules.\n " ]
Please provide a description of the function:def typelogged(memb): if not pytypes.typelogging_enabled: return memb if _check_as_func(memb): return typelogged_func(memb) if isclass(memb): return typelogged_class(memb) if ismodule(memb): return typelogged_module(memb) ...
[ "Decorator applicable to functions, methods, properties,\n classes or modules (by explicit call).\n If applied on a module, memb must be a module or a module name contained in sys.modules.\n See pytypes.set_global_typelogged_decorator to apply this on all modules.\n Observes function and method calls at...
Please provide a description of the function:def enable_global_typechecked_decorator(flag = True, retrospective = True): global global_typechecked_decorator global_typechecked_decorator = flag if import_hook_enabled: _install_import_hook() if global_typechecked_decorator and retrospective: ...
[ "Enables or disables global typechecking mode via decorators.\n See flag global_typechecked_decorator.\n In contrast to setting the flag directly, this function provides\n a retrospective option. If retrospective is true, this will also\n affect already imported modules, not only future imports.\n Do...
Please provide a description of the function:def enable_global_auto_override_decorator(flag = True, retrospective = True): global global_auto_override_decorator global_auto_override_decorator = flag if import_hook_enabled: _install_import_hook() if global_auto_override_decorator and retrosp...
[ "Enables or disables global auto_override mode via decorators.\n See flag global_auto_override_decorator.\n In contrast to setting the flag directly, this function provides\n a retrospective option. If retrospective is true, this will also\n affect already imported modules, not only future imports.\n ...
Please provide a description of the function:def enable_global_annotations_decorator(flag = True, retrospective = True): global global_annotations_decorator global_annotations_decorator = flag if import_hook_enabled: _install_import_hook() if global_annotations_decorator and retrospective: ...
[ "Enables or disables global annotation mode via decorators.\n See flag global_annotations_decorator.\n In contrast to setting the flag directly, this function provides\n a retrospective option. If retrospective is true, this will also\n affect already imported modules, not only future imports.\n " ]
Please provide a description of the function:def enable_global_typelogged_decorator(flag = True, retrospective = True): global global_typelogged_decorator global_typelogged_decorator = flag if import_hook_enabled: _install_import_hook() if global_typelogged_decorator and retrospective: ...
[ "Enables or disables global typelog mode via decorators.\n See flag global_typelogged_decorator.\n In contrast to setting the flag directly, this function provides\n a retrospective option. If retrospective is true, this will also\n affect already imported modules, not only future imports.\n " ]
Please provide a description of the function:def enable_global_typechecked_profiler(flag = True): global global_typechecked_profiler, _global_type_agent, global_typelogged_profiler global_typechecked_profiler = flag if flag and checking_enabled: if _global_type_agent is None: _globa...
[ "Enables or disables global typechecking mode via a profiler.\n See flag global_typechecked_profiler.\n Does not work if checking_enabled is false.\n " ]
Please provide a description of the function:def enable_global_typelogged_profiler(flag = True): global global_typelogged_profiler, _global_type_agent, global_typechecked_profiler global_typelogged_profiler = flag if flag and typelogging_enabled: if _global_type_agent is None: _glob...
[ "Enables or disables global typelogging mode via a profiler.\n See flag global_typelogged_profiler.\n Does not work if typelogging_enabled is false.\n " ]
Please provide a description of the function:def _detect_issue351(): class Tuple(typing.Generic[typing.T]): pass res = Tuple[str] == typing.Tuple[str] del Tuple return res
[ "Detect if github.com/python/typing/issues/351 applies\n to the installed typing-version.\n " ]
Please provide a description of the function:def _preprocess_override(meth_types, base_types, meth_argspec, base_argspec): try: base_kw = base_argspec.keywords kw = meth_argspec.keywords except AttributeError: base_kw = base_argspec.varkw kw = meth_argspec.varkw try: ...
[ "This function linearizes type info of ordinary, vararg, kwonly and varkw\n arguments, such that override-feasibility can be conveniently checked. \n " ]
Please provide a description of the function:def override(func, auto = False): if not pytypes.checking_enabled: return func # notes: # - don't use @override on __init__ (raise warning? Error for now!), # because __init__ is not intended to be called after creation # - @override applie...
[ "Decorator applicable to methods only.\n For a version applicable also to classes or modules use auto_override.\n Asserts that for the decorated method a parent method exists in its mro.\n If both the decorated method and its parent method are type annotated,\n the decorator additionally asserts compati...
Please provide a description of the function:def typechecked_func(func, force = False, argType = None, resType = None, prop_getter = False): if not pytypes.checking_enabled and not pytypes.do_logging_in_typechecked: return func assert(_check_as_func(func)) if not force and is_no_type_check(func...
[ "Works like typechecked, but is only applicable to functions, methods and properties.\n " ]
Please provide a description of the function:def typechecked_class(cls, force = False, force_recursive = False): return _typechecked_class(cls, set(), force, force_recursive)
[ "Works like typechecked, but is only applicable to classes.\n " ]
Please provide a description of the function:def typechecked_module(md, force_recursive = False): if not pytypes.checking_enabled: return md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md in...
[ "Works like typechecked, but is only applicable to modules (by explicit call).\n md must be a module or a module name contained in sys.modules.\n " ]
Please provide a description of the function:def typechecked(memb): if not pytypes.checking_enabled: return memb if is_no_type_check(memb): return memb if type_util._check_as_func(memb): return typechecked_func(memb) if isclass(memb): return typechecked_class(memb) ...
[ "Decorator applicable to functions, methods, properties,\n classes or modules (by explicit call).\n If applied on a module, memb must be a module or a module name contained in sys.modules.\n See pytypes.set_global_typechecked_decorator to apply this on all modules.\n Asserts compatibility of runtime arg...
Please provide a description of the function:def auto_override_class(cls, force = False, force_recursive = False): if not pytypes.checking_enabled: return cls assert(isclass(cls)) if not force and is_no_type_check(cls): return cls # To play it safe we avoid to modify the dict while ...
[ "Works like auto_override, but is only applicable to classes.\n " ]
Please provide a description of the function:def auto_override_module(md, force_recursive = False): if not pytypes.checking_enabled: return md if isinstance(md, str): if md in sys.modules: md = sys.modules[md] if md is None: return md elif md ...
[ "Works like auto_override, but is only applicable to modules (by explicit call).\n md must be a module or a module name contained in sys.modules.\n " ]
Please provide a description of the function:def auto_override(memb): if type_util._check_as_func(memb): return override(memb, True) if isclass(memb): return auto_override_class(memb) if ismodule(memb): return auto_override_module(memb, True) if memb in sys.modules or memb i...
[ "Decorator applicable to methods, classes or modules (by explicit call).\n If applied on a module, memb must be a module or a module name contained in sys.modules.\n See pytypes.set_global_auto_override_decorator to apply this on all modules.\n Works like override decorator on type annotated methods that a...
Please provide a description of the function:def no_type_check(memb): try: return typing.no_type_check(memb) except(AttributeError): _not_type_checked.add(memb) return memb
[ "Works like typing.no_type_check, but also supports cases where\n typing.no_type_check fails due to AttributeError. This can happen,\n because typing.no_type_check wants to access __no_type_check__, which\n might fail if e.g. a class is using slots or an object doesn't support\n custom attributes.\n ...
Please provide a description of the function:def is_no_type_check(memb): try: return hasattr(memb, '__no_type_check__') and memb.__no_type_check__ or \ memb in _not_type_checked except TypeError: return False
[ "Checks if an object was annotated with @no_type_check\n (from typing or pytypes.typechecker).\n " ]
Please provide a description of the function:def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0): return _check_caller_type(False, cllable, call_args, clss, caller_level+1)
[ "Can be called from within a function or method to apply typechecking to\n the arguments that were passed in by the caller. Checking is applied w.r.t.\n type hints of the function or method hosting the call to check_argument_types.\n " ]