Package: py-toolbelt
Py ToolBeltThis module contains basic functions for built-in datatypes for execute trivial tasks.
This functions are available as built-in datatype methods.InstallationInstall package using pip ->pip install py-toolbeltUsageImport the module and activate toolbeltimport py_toolbelt py_toolbelt.activate()After activation, custom functions are available as built-in methods.
For example -
Before activation, in python console, create a list variablelist_object = [1, 2, 3]and typelist_object.and press tab to get prompt of available methods, you see ->>>list_object.l.append(l.clear(l.copy(l.count(l.extend(l.index(l.insert(l.pop(l.remove(l.reverse(l.sort(After activation ->>>list_object.l.append(l.count(l.filter(l.insert(l.pop(l.reverse(l.to_tuple(l.clear(l.count_all(l.flat_list(l.intersection(l.remove(l.sort(l.transform(l.compact(l.execute(l.get_index(l.is_none(l.remove_index(l.to_dict(l.unique(l.copy(l.extend(l.index(l.is_not_none(l.remove_values(l.to_set(To deactivate the toolbeltpy_toolbelt.deactivate()Available FunctionsListunique()Eliminate duplicate elements from list.note -elements should be hashable datatype i.e elements must be str, int, float, tuple, bool only.Example>>>list_obj=[1,2,3,3,2]>>>print(list_obj.unique())[1,2,3]to_set()Convert list to set.note -elements should be hashable datatype i.e elements must be str, int, float, tuple, bool only.Example>>>list_obj=[1,2,3,3,2]>>>print(list_obj.to_set()){1,2,3}to_tuple()Convert list to tuple.note -elements should be hashable datatype i.e elements must be str, int, float, tuple, bool only.Example>>>list_obj=[1,2,3,3,2]>>>print(list_obj.to_tuple())(1,2,3,3,2)to_dict(key_function=None,value_function=None)Convert list to dict with with keys usingkey_functionand values usingvalue_function.Argumentkey_function-function, any number of argument are accepted. (required)value_function-function, any number of arguments are accepted. (required)Example>>>list_obj=[1,2,3,4]>>>list_obj.to_dict(key_function=lambdax:x,value_function=lambday:y*2){1:1,2:4,3:6,4:8}remove_index(index=[],**kwargs)Remove indexes from list based on given index values inindexargument and givenconditionkeyword argument.**note - **conditionis applicable on indexes, not on the elements of listArgumentsindex-list/int, if singleintis given then remove that index, iflistis given then remove indexes given in list. (optional,default:[])Keyword argumentscondition-function, if condition function satisfy for index number then it will be removed.cast-data_type, cast the elements of list.Example>>>list_obj=['hello','this','is','a','list']>>>list_obj.remove_index(1)['hello','is','a','list']>>>list_obj.remove_index([0,1,2])['a','list']>>>list_obj.remove_index(condition=lambdax:x%2==0)# even indexes will be removed['is','list']>>>list_obj=[1,2,3,4]>>>list_obj.remove_index([1,2],condition=lambdax:x%2==0,cast=str)['4']remove_values(values=[],**kwargs)Remove elements from list based on given values inindexargument and givenconditionkeyword argument.Argumentsvalues-list/ any data type, if any other data type is given (except list) then it exclude all occurences, iflistis given then exclude elements if it exist in given list. (optional,default:[])Keyword argumentscondition-function, if condition function satisfy for list element then it will be removed.cast-data_type, cast the elements of list.Example>>>list_obj=['hello','this','is','a','list']>>>list_obj.remove_values('this')['hello','is','a','list']>>>list_obj.remove_values(['hello','this','is'])['a','list']>>>list_obj.remove_values(condition=lambdax:x=='hello')['this','is','a','list']>>>list_obj=[1,2,3,4]>>>list_obj.remove_values([1,2],condition=lambdax:x%2==0,cast=str)['4']filter(condition,**kwargs)Filter list with givenconditionfunction.
It is equivalent to -[element for element in list_object if condition(element)]Argumentscondition-function, if condition function not satisfy for list element then it will be excluded. (required)Keyword argumentscast-data_type, cast the elements of list.Example>>>list_obj=[1,2,3,4,5,6]>>>list_obj.filter(lambdax:x>3)[4,5,6]>>>list_obj.filter(lambdax:x<=3,cast=float)[1.0.2.0.3.0]compact()ExcludeNoneor emptylist/dict/set/tuplefrom list.Example>>>list_obj=[1,2,3,None,[],{}]>>>list_obj.compact()[1,2,3]transform(element_function)Transform the elements of list.Argumentselement_function-function, list elements are passed to given function. (required)Example>>>list_obj=[1,2,3,4]>>>list_obj.transform(lambdax:x**2)[1,4,9,16]>>>list_obj=[*enumerate(list_object)]>>>list_obj.transform(lambdax,y:x+y)[1,3,5,7]count_all()Count occurences of elements in list.note -elements should be hashable datatype i.e elements must be str, int, float, tuple, bool only.Example>>>list_obj=[1,2,2,3,3,4]>>>list_obj.count_all(){1:1,2:2,3:2,4:1}intersection(target_list)Give list of common elements.note -elements should be hashable datatype i.e elements must be str, int, float, tuple, bool only.Example>>>list_obj=[1,2,2,3,3,4]>>>list_obj.intersection([2,4,5,6,7])[2,4]flatten()Convert N-Dimention list into single flat 1-D list.Example>>>list_obj=[1,[2,2],3,[[[3]]],4]>>>list_obj.flatten()[1,2,2,3,3,4]get_index(index,default_value=None)Fetch given index from list, if given index is out of range then returndefault_value.Argumentsindex-int, (required)default_value- any data type, (optional,default: None)Example>>>list_obj=[1,2,3,4,5]>>>list_obj.get_index(2)3>>>list_obj.get_index(10,'N/A')N/Aexecute(execute_function)Execute function using elements of list.Argumentsexecute_function-function, it can accept any number of arguments (required)Example>>>list_obj=[1,2,3,4,5]>>>new_list=[]>>>list_obj.execute(lambdax:new_list.append(x*3))>>>new_list[3,6,9,12,15]>>>list_obj.execute(lambdax:print(x))12345Dictfilter(condition,**kwargs)Filter dict based on keys and values.Argumentscondition-function,functionmust accept 2 parameters, 1st parameter for key and 2nd parameter for value. (required)Example>>>dict_obj={'a':1,'b':2,'c':3}>>>dict_obj.filter(lambdakey,value:value>1){'b':2,'c':3}transform(key_function=None,value_function=None)Transform dict keys and values according to given functions.Argumentskey_function-function,functioncan accept any number of arguments. (optional,default:None)value_function-function,functioncan accept any number of arguments. (optional,default:None)Example>>>dict_obj={'a':1,'b':2,'c':3}>>>dict_obj.transform(key_function=lambdax:'a'+x){'aa':1,'ab':2,'ac':3}>>>dict_obj.transform(value_function=lambdax:x**2){'a':1,'b':4,'c':9}>>>dict_obj={'a':(1,2),'b':(3,4),'c':(5,6)}>>>dict_obj.transform(key_function=lambdakey:key+'_sum',value_function=lambdax,y:x+y){'a_sum':3,'b_sum':7,'c_sum':11}keys_list()Return keys of dict as list.Example>>>dict_obj={'a':1,'b':2,'c':3}>>>dict_obj.keys_list()['a','b','c']values_list()Return values of dict as list.Example>>>dict_obj={'a':1,'b':2,'c':3}>>>dict_obj.values_list()[1,2,3]remove(key_function=None,value_function=None,operator='and')Remove dict keys based on givenkey_functionandvalue_fucntionand operation betweenkey_funcitonandvalue_functionwhich is by defaultandoperation.Argumentskey_function-function,functioncan accept any number of arguments. (optional,default:None)value_function-function,functioncan accept any number of arguments. (optional,default:None)operator-str, accepted string - ['and', 'or'], (optional,default='and')Example>>>dict_obj={'a':1,'b':2,'c':3}>>>dict_obj.remove(key_function=lambdax:x=='b'){'a':1,'c':3}>>>dict_object.remove(key_function=lambdakey:keyin['b','c'],value_fucntion=lambdavalue:value%2==1){'a':1,'b':2}>>>dict_object.remove(key_function=lambdakey:keyin['b','c'],value_fucntion=lambdavalue:value%2==1,operator='or'){'a':1}reverse(keep_duplicate=False)Reverse the dict, set values as keys and keys as values. Ifkeep_duplicateis set true then it will merge duplicate value as list.note -dict values should be hashable datatype i.e elements must be str, int, float, tuple, bool only.Argumentskeep_duplicate-bool, (optional,default:False)Example>>>dict_obj={'a':1,'b':2,'c':3,'d':3}>>>dict_obj.reverse(){1:'a',2:'b',3:'d'}>>>dict_obj.reverse(keep_duplicate=True){1:'a',2:'b',3:['c','d']}deep_merge(target_dict,max_depth=None)It will merge giventarget_dictwith givenmax_depth. Ifmax_depthisNonethen it go down to maximum depth for merging.Argumentstarget_dict-dict, (required)max_depth-int,intgreater than 0, (optional,default:None)Example>>>dict_obj={'a':1,'b':{'c':{'d':3},'e':2}}>>>dict_obj.deep_merge({'g':4,'b':{'c':{'d':5}}}){'a':1,'b':{'c':{'d':[3,5]},'e':2},'g':4}>>>dict_obj.deep_merge({'g':4,'b':{'c':{'d':5}}},max_depth=1){'a':1,'b':[{'c':{'d':3},'e':2},{'c':{'d':5}}],'g':4}execute(execute_function)Execute function using keys and values of dict.Argumentsexecute_function-function, it must accept 2 arguments key and value, (required)Example>>>dict_obj={'a':1,'b':2,'c':3}>>>new_list=[]>>>dict_obj.execute(lambdax,y:new_list.append(y))>>>new_list[1,2,3]>>>dict_obj.execute(lambdax,y:print(x))123Setto_list()Convert set to list.Tupleto_list()Convert tuple to list.Int & Floatis_positive(**kwargs)ReturnTrueif number is positive else returnFalse. Ifon_trueoron_falsekeyword arguments are present then it will return keyword argument value respectively.Keyword argumentson_true- any data type, (optional,default:True)on_false- any data type, (optional,default:False)Example>>>num=1>>>num.is_positive()True>>>num.is_positive(on_true='Yes')Yes>>>num=-9>>>num.is_positive(on_false='No')No>>>num.is_positive(on_true='Yes')Falseis_negetive(**kwargs)ReturnTrueif number is negetive else returnFalse. Ifon_trueoron_falsekeyword arguments are present then it will return keyword argument value respectively.Keyword argumentson_true- any data type, (optional,default:True)on_false- any data type, (optional,default:False)Example>>>num=1>>>num.is_negetive()False>>>num.is_negetive(on_true='Yes')False>>>num=-9>>>num.is_negetive(on_false='No')True>>>num.is_negetive(on_true='Yes',on_false='No')Yesis_zero(**kwargs)ReturnTrueif number is equal to zero else returnFalse. Ifon_trueoron_falsekeyword arguments are present then it will return keyword argument value respectively.Keyword argumentson_true- any data type, (optional,default:True)on_false- any data type, (optional,default:False)Example>>>num=1>>>num.is_zero()False>>>num.is_zero(on_true='Yes')False>>>num=0>>>num.is_zero(on_false='No')True>>>num.is_zero(on_true='Yes',on_false='No')Yessafe_divide(denominator,default=math.nan)It ensure ifdenominatoris zero then returndefaultvalue otherwise return divided value.Argumentsdenominator-int/float, (required)default- any data type, (optional,default:math.nan)Example>>>a=4>>>a.safe_divide(2)2.0>>>a.safe_divide(0)nan>>>a.safe_divide(0,0)0>>>a.safe_divde(0,'N/A')N/AOthersThis is common to all data types -is_none(**kwargs)ReturnTrueif object isNoneelse returnFalse. Ifon_trueoron_falsekeyword arguments are present then it will return keyword argument value respectively.Keyword argumentson_true- any data type, (optional,default:True)on_false- any data type, (optional,default:False)Example>>>a,b,c,d=2,'hello',[],None>>>a.is_none()False>>>a.is_none(on_false=a+1)3>>>b.is_none(on_true="Yes")False>>>d.is_none()Trueis_not_none(**kwargs)ReturnTrueif object is notNoneelse returnFalse. Ifon_trueoron_falsekeyword arguments are present then it will return keyword argument value respectively.Keyword argumentson_true- any data type, (optional,default:True)on_false- any data type, (optional,default:False)Example>>>a,b,c,d=2,'hello',[],None>>>a.is_not_none()True>>>a.is_not_none(on_false=a+1)True>>>b.is_not_none(on_true="Yes")Yes>>>d.is_not_none()False_s_sattribute is use to access any object attribute safely access._s(*args, *kwargs)to safely call a method on the object
You can use as None-aware operation.ExampleclassAclass:def__init__(self):self.a,self.b_=1,2>>>obj=Aclass()>>>obj.a# Attribute `a` exists in object1>>>obj.hello# Attribute `hello` does not existsTraceback(mostrecentcalllast):File"<stdin>",line1,in<module>AttributeError:'Aclass'objecthasnoattribute'hello'>>>obj._s.hello# Accessing a non-existing attribute via `_s` attribute. It will return None>>>obj._s.hello._s.world._s.chain_whatever# Consecutive chaining also evaluate None>>>obj._s.a# Attribute `a` exist so it will return its value.1>>>str_value='hello'>>>str_value.find('e')# find method exists on string object.1>>>str_value.find_new('e')# find_new method does not exists so it will raise errorTraceback(mostrecentcalllast):File"<stdin>",line1,in<module>AttributeError:'str'objecthasnoattribute'find_new'>>>str_value.find_new._s('e')# Using _s(*args, **kwarg) to safely call the method and it will return None.Functions toolbeltis_type(obj,target_obj)ReturnTrueif object matches with given types else returnFalse.Argumentsobj- any data type / objecttarget_obj- string or list of stringExample>>>a,b,c=2,'hello',['world']>>>is_type(a,'int')True>>>is_type(b,'int')False>>>is_type(c,['list','set'])True>>>is_type(a,['str','list'])Falsehandle_division(numerator,denominator,default=0)Return division value ifdenominatoris not zero otherwise returndefaultvalue.Argumentsnumerator- int / floatdenominator- int / floatdefault- int / float, (optional,default:0)Example>>>handle_division(1,2)0.5>>>handle_division(1.5,None)0>>>handle_division(2,0,2)2>>>handle_division(2,0)0multithread_pool(funcs,max_threads=5)This method execute givenfuncsdict of functions in multi-thread. Each thread execute one function.Argumentsfuncs- dictmax_threads- int, (optional,default:5)Examplefuncsargument dict keys are function and value is either list of length 2 orNone.
List 1st element should be list of positional arguments.
List 2nd element should be dict of keyword arguments.
If key isNonethen it means function do not take any positional arguments and keyword
arguments.
Structure -{test_func1:[[1,2,'Hello',[1,2,333]],{'arg_key':12}],test_func2:[[1,2,'Hello',[1,2,333]],test_func3:[None,{'arg_key':123}],}test_func:None}cache_db(key,value=None)This function use to implement temporary small pickle database which is a json storing file.
This is not persistant database so it will be cleared out if you deploy new code / delete the pickle file.
So make sure to use in such cases where you need data to store for temporary purpose.
This function accept two parameters, first iskeyand second isvalue.
If onlykeyparameter is provided then it will get data from database, ifkeynot found returnFalse, otherwise return key's value.
If you pass bothkeyandvalueparameters then it will set key value in database.Argumentskey- strvalue- any basic datatype accepted by json format, (optional,default:None)Example>>>cache_db(key='hello')False>>>cache_db(key='hello',value='world')True>>>cache_db(key='hello')Worldnone_safe(object,default=None)If givenobjectis notNonethen return object otherwise returndefaultvalue.Argumentsobject- any data type / objectdefault- any data type / object, (optional,default:None)Example>>>none_safe(5)5>>>none_safe('hello','world')hello>>>none_safe(None,'world')worlditer_safe(object,default=[])If givenobjectis notNoneand object is instance of iterable then return object otherwise returndefaultvalue.Argumentsobject- any data type / objectdefault- any data type / object, (optional,default:[])Example>>>iter_safe(5)[]>>>iter_safe(['hello'],'world')['hello']>>>iter_safe([],'world')[]>>>iter_safe('hello')'hello'>>>iter_safe(1.4,['hello','world'])['hello','world']empty_safe(object,default=None)If givenobjectis empty in sense of iterable then returndefaultvalue else returnobject.Argumentsobject- any data type / objectdefault- any data type / object, (optional,default:None)Example>>>empty_safe(5)5>>>empty_safe(['hello'],'world')['hello']>>>empty_safe([],'world')'world'>>>empty_safe('hello')'hello'>>>empty_safe(1.4,['hello','world'])1.4MIT LicenseCopyright (c) 2021 Soami CharanPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.