PK!\ʹ00all_purpose_dict/__init__.pyfrom .index import ApDict __all__ = ["ApDict"] PK!M&& all_purpose_dict/fns/__init__.pyfrom .discardWhen import discardWhen from .isLaden import isLaden from .joinWith import joinWith from .map_ import map_ from .passThrough import passThrough from .raise_ import raise_ __all__ = [ "discardWhen", "isLaden", "joinWith", "map_", "passThrough", "raise_", ] PK!+all_purpose_dict/fns/decorators/__init__.pyPK![`)gEE0all_purpose_dict/fns/decorators/argIsCallable.pyfrom inspect import signature import wrapt @wrapt.decorator def argIsCallable(fn, _instance, args, kwargs): if not callable(args[0]): argName = list(signature(fn).parameters)[0] fnName = fn.__name__ raise ValueError(f"{fnName} requires {argName} to be callable") return fn(*args, **kwargs) PK!waII-all_purpose_dict/fns/decorators/argIsClass.pyfrom inspect import isclass, signature import wrapt @wrapt.decorator def argIsClass(fn, _instance, args, kwargs): if not isclass(args[0]): argName = list(signature(fn).parameters)[0] fnName = fn.__name__ raise ValueError(f"{fnName} requires {argName} to be a class") return fn(*args, **kwargs) PK!2all_purpose_dict/fns/decorators/argIsListOfType.pyfrom ordered_set import OrderedSet import wrapt from ..internal.discardWhen import discardWhen from ..internal.get import get from ..internal.getArgName import getArgName from ..internal.isLaden import isLaden from ..internal.isType import isType from ..internal.joinWith import joinWith from ..internal.map_ import map_ from ..internal.passThrough import passThrough from ..internal.raise_ import raise_ from ..internal.sort import sort from ..internal.toType import toType def argIsListOfType(aType): @wrapt.decorator def wrapper(fn, _instance, args, kwargs): typePassed = type(args[0]) fnName = fn.__name__ typeName = aType.__name__ if typePassed is not list: argName = getArgName(fn) raise_( ValueError, f"""\ {fnName} requires {argName} to have the type list type passed: {typePassed.__name__} """, ) invalidTypes = discardWhen(isType(aType))(args[0]) if isLaden(invalidTypes): argName = getArgName(fn) invalidTypeNames = passThrough( invalidTypes, [ map_(toType), OrderedSet, list, map_(get("__name__")), sort, joinWith(", "), ], ) raise_( ValueError, f"""\ {fnName} requires {argName} to be a list of {typeName} invalid types passed: {invalidTypeNames} """, ) return fn(*args, **kwargs) return wrapper PK!)ʋ,all_purpose_dict/fns/decorators/argIsType.pyfrom inspect import signature from ..internal.raise_ import raise_ import wrapt def argIsType(aType): @wrapt.decorator def wrapper(fn, _instance, args, kwargs): typePassed = type(args[0]) if typePassed is not str: argName = list(signature(fn).parameters)[0] fnName = fn.__name__ typeName = aType.__name__ raise_( ValueError, f"""\ {fnName} requires {argName} to have the type {typeName} type passed: {typePassed.__name__} """, ) return fn(*args, **kwargs) return wrapper PK!| ;;#all_purpose_dict/fns/discardWhen.pyfrom .internal.discardWhen import discardWhen # noqa f401 PK!)all_purpose_dict/fns/internal/__init__.pyPK!F,all_purpose_dict/fns/internal/discardWhen.py# ------- # # Imports # # ------- # from .getTypedResult import getTypedResult from .makeGenericCallFn import makeGenericCallFn from ..decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def discardWhen(predicate): fnName = discardWhen.__name__ shouldDiscard = makeGenericCallFn(predicate, 3, fnName) def discardWhen_inner(collection): typedDiscardWhen = getTypedResult(collection, typeToDiscardWhen, fnName) return typedDiscardWhen(shouldDiscard, collection) return discardWhen_inner # ------- # # Helpers # # ------- # def discardWhen_list(shouldDiscard, aList): result = [] for idx, el in enumerate(aList): if not shouldDiscard(el, idx, aList): result.append(el) return result def discardWhen_dict(shouldDiscard, aDict): result = {} for key, val in aDict.items(): if shouldDiscard(val, key, aDict): result[key] = val return result typeToDiscardWhen = {list: discardWhen_list, dict: discardWhen_dict} PK!ss$all_purpose_dict/fns/internal/get.pydef get(attrName): def get_inner(something): return getattr(something, attrName) return get_inner PK!)jj+all_purpose_dict/fns/internal/getArgName.pyfrom inspect import signature def getArgName(fn, idx=0): return list(signature(fn).parameters)[idx] PK!X/all_purpose_dict/fns/internal/getFnSignature.pyfrom inspect import signature from .raise_ import raise_ def getFnSignature(fn, callerName): try: return signature(fn) except Exception as e: raise_( ValueError, f"""\ '{callerName}' is unable to get the signature of the passed callable callable passed: {fn.__name__} one reason this could occur is the callable is written in c (e.g. the builtin 'str' callable). """, fromException=e, ) PK!k7all_purpose_dict/fns/internal/getNumPositionalParams.py# ------- # # Imports # # ------- # from inspect import Parameter from math import inf from .getFnSignature import getFnSignature from .iif import iif # ---- # # Init # # ---- # _nonVarPositionalParamKinds = { Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD, } # ---- # # Main # # ---- # # # Returns a tuple # numRequired: number of required positional params # numAllowed: number of allowed positional params # def getNumPositionalParams(fn, callerName): sig = getFnSignature(fn, callerName) numAllowed = iif(_hasVarPositionalParam(sig), inf, 0) numRequired = 0 for p in sig.parameters.values(): if p.kind in _nonVarPositionalParamKinds: numAllowed += 1 if p.default is Parameter.empty: numRequired += 1 return (numRequired, numAllowed) # ------- # # Helpers # # ------- # def _hasVarPositionalParam(sig): for p in sig.parameters.values(): if p.kind is Parameter.VAR_POSITIONAL: return True PK!w</all_purpose_dict/fns/internal/getTypedResult.py# # README # - I'm not sure what to call this. Its purpose is to centralize the type # validation, minimizing copy/paste. # # ------- # # Imports # # ------- # from .raise_ import raise_ from .get import get # ---- # # Init # # ---- # getName = get("__name__") # # we need a unique object here to ensure the 'typeToSomething' doesn't lead us # to a 'None' value # nothing = object() # ---- # # Main # # ---- # def getTypedResult(value, typeToSomething, fnName): valueType = type(value) result = typeToSomething.get(valueType, nothing) if _isSomething(result): return result supportedTypes = ", ".join(map(getName, typeToSomething.keys())) raise_( ValueError, f"""\ {fnName} doesn't support the type '{valueType.__name__}' supported types: {supportedTypes} """, ) # ------- # # Helpers # # ------- # def _isSomething(x): return x is not nothing PK!;||$all_purpose_dict/fns/internal/iif.pydef iif(condition, whenTruthy, whenFalsey): if condition: return whenTruthy else: return whenFalsey PK!ws{33(all_purpose_dict/fns/internal/isLaden.pydef isLaden(aList): return len(aList) is not 0 PK!Ȋ1all_purpose_dict/fns/internal/isOnlyWhitespace.pyimport re onlyWhitespaceRe = re.compile(r"\s*$") def isOnlyWhitespace(aString): return onlyWhitespaceRe.match(aString) is not None PK!f'all_purpose_dict/fns/internal/isType.pyfrom inspect import isclass def isType(aType): if not isclass(aType): raise ValueError("isType requires argument 'aType' to pass isclass") def isType_inner(something): return type(something) is aType return isType_inner PK!v_R*++)all_purpose_dict/fns/internal/joinWith.py# ------- # # Imports # # ------- # from ordered_set import OrderedSet from .getTypedResult import getTypedResult # ---- # # Main # # ---- # def joinWith(separator): def joinWith_inner(collection): typedJoinWith = getTypedResult(collection, typeToJoinWith, "joinWith") return typedJoinWith(separator, collection) return joinWith_inner # ------- # # Helpers # # ------- # def joinWith_iterable(separator, aList): return separator.join(aList) typeToJoinWith = {list: joinWith_iterable, OrderedSet: joinWith_iterable} PK!K+all_purpose_dict/fns/internal/makeCallFn.py# ------- # # Imports # # ------- # from math import inf from .returnFirstArgument import returnFirstArgument as identity from .getNumPositionalParams import getNumPositionalParams # ---- # # Main # # ---- # def makeCallFn(fn, callerName, *, modifyResult=identity): (_, allowed) = getNumPositionalParams(fn, callerName) if allowed is inf: return lambda *args, **kwargs: modifyResult(fn(*args, **kwargs)) else: return lambda *args, **kwargs: modifyResult( fn(*args[:allowed], **kwargs) ) PK!T-2all_purpose_dict/fns/internal/makeGenericCallFn.py# ------- # # Imports # # ------- # from math import inf from .getNumPositionalParams import getNumPositionalParams from .raise_ import raise_ # ---- # # Main # # ---- # def makeGenericCallFn(fn, maxParams, callerName): required, allowed = getNumPositionalParams(fn, callerName) if allowed is inf: allowed = maxParams if required > maxParams: raise_( ValueError, f""" {callerName} can only take functions with up to {maxParams} positional params. The function '{fn.__name__}' requires {required} """, ) return lambda *args, **kwargs: fn(*args[:allowed], **kwargs) PK!G~%all_purpose_dict/fns/internal/map_.py# ------- # # Imports # # ------- # from .makeGenericCallFn import makeGenericCallFn from .getTypedResult import getTypedResult from ..decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def map_(mapperFn): fnName = map_.__name__ callMapperFn = makeGenericCallFn(mapperFn, 3, fnName) def map_inner(collection): typedMap = getTypedResult(collection, typeToMap, fnName) return typedMap(callMapperFn, collection) return map_inner # ------- # # Helpers # # ------- # def map_list(callMapperFn, aList): result = [] for idx, el in enumerate(aList): result.append(callMapperFn(el, idx, aList)) return result typeToMap = {list: map_list} PK!yy,all_purpose_dict/fns/internal/passThrough.pyfrom .reduce import reduce def passThrough(arg, fnList): return reduce(lambda result, fn: fn(result), arg)(fnList) PK!W'all_purpose_dict/fns/internal/raise_.pyfrom tedent import tedent from .isOnlyWhitespace import isOnlyWhitespace import os def raise_(errorClass, message, *, fromException=None): allLines = message.split(os.linesep) if isOnlyWhitespace(allLines[0]) and isOnlyWhitespace(allLines[-1]): message = tedent(message) err = errorClass(message) if fromException is None: raise err else: raise err from fromException PK!Et'all_purpose_dict/fns/internal/reduce.py# ------- # # Imports # # ------- # from .makeGenericCallFn import makeGenericCallFn from .getTypedResult import getTypedResult from ..decorators.argIsCallable import argIsCallable # ---- # # Main # # ---- # @argIsCallable def reduce(fn, initial): reducerFn = makeGenericCallFn(fn, 4, "reduce") def reduce_inner(collection): typedReduce = getTypedResult(collection, typeToReduce, "reduce") return typedReduce(reducerFn, initial, collection) return reduce_inner # ------- # # Helpers # # ------- # def reduce_list(reducerFn, initial, aList): result = initial for idx, el in enumerate(aList): result = reducerFn(result, el, idx, aList) return result typeToReduce = {list: reduce_list} PK!pjj4all_purpose_dict/fns/internal/returnFirstArgument.pyfrom .iif import iif def returnFirstArgument(*args, **kwargs): return iif(len(args), args[0], None) PK!\xx0all_purpose_dict/fns/internal/sanitizeAscDesc.pyfrom .raise_ import raise_ ascDescSet = {"asc", "desc"} def sanitizeAscDesc(ascOrDesc): sanitized = ascOrDesc.lower() if sanitized not in ascDescSet: raise_( ValueError, f""" ascOrDesc must be either 'asc' or 'desc' (case insensitive) value given: {ascOrDesc} """, ) return sanitized PK!0oo%all_purpose_dict/fns/internal/sort.py# ------- # # Imports # # ------- # from .getTypedResult import getTypedResult # ---- # # Main # # ---- # def sort(collection): typedSort = getTypedResult(collection, typeToSort, "sort") return typedSort(collection) # ------- # # Helpers # # ------- # def sort_viaSorted(something): return sorted(something) typeToSort = {list: sort_viaSorted} PK!V;22'all_purpose_dict/fns/internal/toType.pydef toType(something): return type(something) PK!X33all_purpose_dict/fns/isLaden.pyfrom .internal.isLaden import isLaden # noqa f401 PK!955 all_purpose_dict/fns/joinWith.pyfrom .internal.joinWith import joinWith # noqa f401 PK!}--all_purpose_dict/fns/map_.pyfrom .internal.map_ import map_ # noqa f401 PK!F;;#all_purpose_dict/fns/passThrough.pyfrom .internal.passThrough import passThrough # noqa f401 PK!(11all_purpose_dict/fns/raise_.pyfrom .internal.raise_ import raise_ # noqa f401 PK!all_purpose_dict/index.py# ------- # # Imports # # ------- # from ordered_set import OrderedSet from .fns import discardWhen, isLaden, raise_ from . import iterators # ---- # # Main # # ---- # class ApDict: def __init__(self, listOfPairs=[]): validateListOfPairs(listOfPairs) # # _orderedKeys holds a set of tuples (hashable: boolean, key) # where key is the id of the key when hashable is false # self._orderedKeys = OrderedSet() self._hashableData = {} self._nonHashableData = {} self._populateData(listOfPairs) def _populateData(self, listOfPairs): for key, value in listOfPairs: self._set(key, value) def _set(self, key, value): try: self._hashableData[key] = value self._orderedKeys.add((True, key)) except: self._nonHashableData[id(key)] = (key, value) self._orderedKeys.add((False, id(key))) return self def __contains__(self, key): return self.has(key) def __delitem__(self, key): return self.delete(key) def __getitem__(self, key): return self.get(key) def __iter__(self): return iterators.ApDictIterator(self) def __len__(self): return len(self._orderedKeys) def __setitem__(self, key, value): return self.set(key, value) def clear(self): self._hashableData.clear() self._nonHashableData.clear() self._orderedKeys.clear() return self def delete(self, key): keyRemoved = False try: if key in self._hashableData: keyRemoved = True self._orderedKeys.discard((True, key)) del self._hashableData[key] except: if id(key) in self._nonHashableData: keyRemoved = True self._orderedKeys.discard((False, id(key))) del self._nonHashableData[id(key)] if not keyRemoved: raise KeyError(f"the key '{str(key)}' does not exist in ApDict") return self def get(self, key): try: if key in self._hashableData: return self._hashableData[key] except: if id(key) in self._nonHashableData: return self._nonHashableData[id(key)][1] raise KeyError(f"the key '{str(key)}' does not exist in ApDict") def has(self, key): try: return key in self._hashableData except: return id(key) in self._nonHashableData def keysIterator(self): return iterators.ApDictKeysIterator(self) def set(self, key, value): return self._set(key, value) def valuesIterator(self): return iterators.ApDictValuesIterator(self) # ------- # # Helpers # # ------- # def validateListOfPairs(listOfPairs): if not isinstance(listOfPairs, list): raise_( ValueError, f""" listOfpairs is not an instance of list type given: {type(listOfPairs)} """, ) invalidElements = discardWhen(isListOrTupleOfLen2)(listOfPairs) if isLaden(invalidElements): n = len(invalidElements) if n == 1: singleOrPlural = "element which isn't" else: singleOrPlural = "elements which aren't" raise_( ValueError, f""" listOfPairs has {n} {singleOrPlural} a list or tuple of length 2 first invalid element: {str(invalidElements[0])} """, ) def isListOrTupleOfLen2(something): return ( isinstance(something, list) or isinstance(something, tuple) ) and len(something) == 2 PK!c@}}all_purpose_dict/iterators.pyclass ApDictIterator: def __init__(self, apDictInst): self._inst = apDictInst self._orderedKeysIterator = iter(apDictInst._orderedKeys) def __iter__(self): return self def __next__(self): hashable, keyOrId = next(self._orderedKeysIterator) if hashable: key = keyOrId value = self._inst._hashableData[keyOrId] else: key = self._inst._nonHashableData[keyOrId][0] value = self._inst._nonHashableData[keyOrId][1] return (key, value) class ApDictKeysIterator: def __init__(self, apDictInst): self._inst = apDictInst self._orderedKeysIterator = iter(apDictInst._orderedKeys) def __iter__(self): return self def __next__(self): hashable, keyOrId = next(self._orderedKeysIterator) if hashable: return keyOrId else: return self._inst._nonHashableData[keyOrId][0] class ApDictValuesIterator: def __init__(self, apDictInst): self._inst = apDictInst self._orderedKeysIterator = iter(apDictInst._orderedKeys) def __iter__(self): return self def __next__(self): hashable, keyOrId = next(self._orderedKeysIterator) if hashable: return self._inst._hashableData[keyOrId] else: return self._inst._nonHashableData[keyOrId][1] PK!4 Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO BUT IT'S NOT MY FAULT PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. 1. Do not hold the author(s), creator(s), developer(s) or distributor(s) liable for anything that happens or goes wrong with your use of the work. PK!HڽTU&all_purpose_dict-0.1.3.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H,$[ )all_purpose_dict-0.1.3.dist-info/METADATAVmOG~b+a#΄R$+*VRH>wc&w=3{I _vvg{)l6Հ^*y@(⺱qg:FE*nR倆$siaWG sɕմ`RUF+/]ΔjpaL)LLUGd>+ŧq4l|n.s].v%TPou/9?mŗKh9=,^[UULȃ|z~c3rvSW9-qᛗ_8Շ]1]ju1T+'a_3Câ֖6:$׎26% Sv4/8[r}^n~t:HYRj.iN5ڄtҴ3>gƖJj:ԞOqL*TIi~F)+'0嚐X(%xi|6u&!xv1OlPntMb|Hur>|XkT)q[u||o5NC[J+i'vվ'.2ʎ:+rp(I>SŎhuM P,N>g6pE0L&;r9!p`DY&zK| hA ݨ( A)̬)eMAXOú'Rkӽdֻvj4oTBЖ( GOXa5,6 ]f{~] KӀsTHV0`u&@ Z@PhT*_I}m@p,A8= Ng׏:dIoQTsb!>/oˆtD҇LOO6x3+9{ԁhg NuΉQFh +P_{IY0:TХ}kKi%yz;2<*yBSjPa ,Bu( $i{롚[E[  ޱG4hi:l&rJ2E_]H09?*ʸ aOe] fKs31s2*%?VΕZ\il;C&.oH+$O~+1FsO㿼p*|6$vTRL!%河yB3ѐ. ,i:JZɺWٔ` u{&tVM'k]aރn͞P# ڀ=OTj1}3>ct_Icz{];GNӭ۞ tZT'O2r@'X"Dɰć1 k<;l^ҎǒEyd$R#ru)_5"#IHmyk h̕o\L u+&So r*\ɘs\c \WRcd,~cˋsSHAs!OZ*( ݿȻqާ⎢O6-ٖi}H/SQ;'QS?xs=兒$q~Nܫ:+14hVp^B+2CJ4G=mf(홍2uo_yJ^-zQLKX,tCȖ5OqDsyF(=9c<-Yl6Sc2*l3%:̜Qzb0fO'uhV'_Vͻ:̬lvɰ?D% bYN}m gwT]3y@Mw2xt'%@H`ˢiKPK!\ʹ00all_purpose_dict/__init__.pyPK!M&& jall_purpose_dict/fns/__init__.pyPK!+all_purpose_dict/fns/decorators/__init__.pyPK![`)gEE0all_purpose_dict/fns/decorators/argIsCallable.pyPK!waII-all_purpose_dict/fns/decorators/argIsClass.pyPK!2>all_purpose_dict/fns/decorators/argIsListOfType.pyPK!)ʋ,; all_purpose_dict/fns/decorators/argIsType.pyPK!| ;;#all_purpose_dict/fns/discardWhen.pyPK!)all_purpose_dict/fns/internal/__init__.pyPK!F,all_purpose_dict/fns/internal/discardWhen.pyPK!ss$9all_purpose_dict/fns/internal/get.pyPK!)jj+all_purpose_dict/fns/internal/getArgName.pyPK!X/all_purpose_dict/fns/internal/getFnSignature.pyPK!k7all_purpose_dict/fns/internal/getNumPositionalParams.pyPK!w</Iall_purpose_dict/fns/internal/getTypedResult.pyPK!;||$E all_purpose_dict/fns/internal/iif.pyPK!ws{33(!all_purpose_dict/fns/internal/isLaden.pyPK!Ȋ1|!all_purpose_dict/fns/internal/isOnlyWhitespace.pyPK!f'U"all_purpose_dict/fns/internal/isType.pyPK!v_R*++)#all_purpose_dict/fns/internal/joinWith.pyPK!K+&all_purpose_dict/fns/internal/makeCallFn.pyPK!T-2o(all_purpose_dict/fns/internal/makeGenericCallFn.pyPK!G~%`+all_purpose_dict/fns/internal/map_.pyPK!yy,.all_purpose_dict/fns/internal/passThrough.pyPK!W'B/all_purpose_dict/fns/internal/raise_.pyPK!Et''1all_purpose_dict/fns/internal/reduce.pyPK!pjj4U4all_purpose_dict/fns/internal/returnFirstArgument.pyPK!\xx05all_purpose_dict/fns/internal/sanitizeAscDesc.pyPK!0oo%6all_purpose_dict/fns/internal/sort.pyPK!V;22'8all_purpose_dict/fns/internal/toType.pyPK!X339all_purpose_dict/fns/isLaden.pyPK!955 p9all_purpose_dict/fns/joinWith.pyPK!}--9all_purpose_dict/fns/map_.pyPK!F;;#J:all_purpose_dict/fns/passThrough.pyPK!(11:all_purpose_dict/fns/raise_.pyPK!3;all_purpose_dict/index.pyPK!c@}}Jall_purpose_dict/iterators.pyPK!4