Package: plazy
plazyUtilities for lazy Python developerspip install plazyIndexCodingplazy.random_string(size=6, digit=True, lower=True, upper=True)plazy.setattr_from_dict(obj, kv, override=True)@plazy.auto_assign@plazy.auto_assign_strict@plazy.cloneableplazy.tic(*names)plazy.toc(*names, default=0)plazy.ts2dt(ts, format="%Y/%m/%d %H:%M:%S.%f")plazy.dt2ts(dt, format="%Y/%m/%d %H:%M:%S.%f")Dataplazy.b64encode(value, pretty=False)plazy.b64decode(value)plazy.is_number(s)plazy.unique(seq, sort=False, reverse=False)Fileplazy.read_txt(path, line_func=None, skip_empty_line=False)plazy.write_txt(path, lines, mode="w", cat_str="\n")plazy.list_files(root, filter_func=None, is_include_root=False)PLAZY FEATURESCodingrandom_stringPlazy version: 0.1.2+Generate random string.plazy.random_string(size: length of random string. Default: 6digit: random string may contains digits. Default: Truelower: random string may contains lowercases. Default: Trueupper: random string may contains uppercases. Default: True)importplazyif__name__=="__main__":rstring=plazy.random_string()# iVr3FYrstring=plazy.random_string(upper=False)# mzvn7brstring=plazy.random_string(size=8)# XqVDuu5Rrstring=plazy.random_string(size=6,digit=True,lower=False,upper=False)# 763099rstring=plazy.random_string(size=6,digit=False,lower=True,upper=False)# djzcchrstring=plazy.random_string(size=6,digit=False,lower=False,upper=True)# BGBMQN:link: Back to Indexsetattr_from_dictPlazy version: 0.1.4+Dynamically set object attributes from dictionary at runtimeplazy.setattr_from_dict(obj: objectkv: dictionary of new attributes. Eg: {"name": "Peter", "age": 14}override: override old attribute(s). Default: True)importplazy# Our custom classclassPerson(object):def__init__(self,name):self.name=nameif__name__=="__main__":p1=Person(name="plazy")# init a Person objectplazy.setattr_from_dict(obj=p1,kv={"name":"yzalp","age":28,})print(p1.name)# "yzalp"print(p1.age)# 28# set "override" to Falsep2=Person(name="plazy")# init a Person objectplazy.setattr_from_dict(obj=p2,override=False,kv={"name":"yzalp","age":28,})print(p1.name)# "plazy" <- no overriding the pre-existed attribute due to "override=False"print(p1.age)# 28:link: Back to Indexauto_assignPlazy version: 0.1.5+Assign attributes of class with the passed arguments automatically.@plazy.auto_assignimportplazyclassCat(object):@plazy.auto_assigndef__init__(self,name,owner='Kyzas'):# no variable assignment neededpassdefget_age(self):returnself.ageifhasattr(self,"age")elseNonedefget_type(self):returnself.typeifhasattr(self,"type")elseNoneif__name__=="__main__":mydict={"type":"pet"}my_cat=Cat('Kittie',age=10,**mydict)# "age" and "type" is unexpected argumentsprint(my_cat.name)# Kittieprint(my_cat.owner)# Kyzasprint(my_cat.get_age())# 10print(my_cat.get_type())# pet:link: Back to Indexauto_assign_strictPlazy version: 0.1.5+Assign attributes of class with the passed arguments automatically, strictly check the parameters passed to the function.@plazy.auto_assign_strictimportplazyclassCat(object):@plazy.auto_assign_strictdef__init__(self,name,owner='Kyzas'):passif__name__=="__main__":my_cat=Cat('Kittie','Minh')print(my_cat.name)# Kittieprint(my_cat.owner)# Minhhis_cat=Cat('Lulu','Peter','Mary')# TypeErrorher_cat=Cat('Kittie',age=10)# TypeError:link: Back to IndexcloneablePlazy version: 0.1.5+Mark constructor of class as being cloneable. Method "clone" is used to clone a new instance, its arguments are the same with the constructor.@plazy.cloneableimportplazyclassCat(object):@plazy.cloneabledef__init__(self,name,owner='Kyzas'):self.name=nameself.owner=ownerpassdefget_info(self):return{"name":self.name,"owner":self.owner}classDog(object):# combine auto_assign and cloneable decorators@plazy.cloneable@plazy.auto_assigndef__init__(self,name,owner='Kyzas'):passdefget_info(self):result={"name":self.name,"owner":self.owner}ifhasattr(self,"age"):result["age"]=self.ageelse:result["age"]=-1returnresultif__name__=="__main__":cat_template=Cat('<Cat Name>','<Owner Name>')his_cat=cat_template.clone('Lulu','Peter')her_cat=cat_template.clone(name='Jessie')print(his_cat.get_info())# {'name': 'Lulu', 'owner': 'Peter'}print(her_cat.get_info())# {'name': 'Jessie', 'owner': '<Owner Name>'}dog_template=Dog(name="<Dog Name>",owner="<Owner Name>",age=10)# age=10 by defaulthis_dog=dog_template.clone(owner='James')her_dog=dog_template.clone(name="Husky",owner="Bella",age=5,note="Super Cute")print(his_dog.get_info())# {'name': '<Dog Name>', 'owner': 'James', 'age': 10}print(her_dog.get_info())# {'name': 'Husky', 'owner': 'Bella', 'age': 5}print(her_dog.note)# Super Cute:link: Back to IndexticPlazy version: 0.1.5+Start timerplazy.tic(*names: name (list))importplazydeffoo():total=0for_inrange(100000):total+=1returntotalif__name__=="__main__":plazy.tic()# T1plazy.tic("B")# T2plazy.tic("C","D","E")# T3foo()dt1=plazy.toc()# elapsed time since T1dt2=plazy.toc("B")# elapsed time since T2dt3=plazy.toc("C","D")# elapsed time since T3foo()dt4=plazy.toc("E")# elapsed time since T3dt5=plazy.toc("B")# elapsed time since T2print(dt1)# 0.009924173355102539print(dt2)# 0.009925603866577148print(dt3)# [0.00992727279663086, 0.00992727279663086]print(dt4)# 0.020497798919677734print(dt5)# 0.020506620407104492:link: Back to IndextocPlazy version: 0.1.5+Get elapsed time(s) by name(s)plazy.toc(*names: name (list)default: default value if name not found. Default: 0)importplazydeffoo():total=0for_inrange(100000):total+=1returntotalif__name__=="__main__":plazy.tic()foo()elapsed_seconds=plazy.toc()# 0.0098724365234375elapsed_invalid=plazy.toc("B",default=-1)# -1 (name "B" does not exist, return default value):link: Back to Indexts2dtPlazy version: 0.1.5+Convert timestamp to datetime stringplazy.ts2dt(ts: timestamp stringformat: datetime format. Default: "%Y/%m/%d %H:%M:%S.%f")importtimeimportplazyif__name__=="__main__":res=plazy.ts2dt(time.time())# 2021/08/28 08:48:05.451271:link: Back to Indexdt2tsPlazy version: 0.1.5+Convert datetime object / datetime string to timestampplazy.dt2ts(dt: datetime object or datetime stringformat: datetime format. Default: "%Y/%m/%d %H:%M:%S.%f")importtimeimportplazyif__name__=="__main__":res=plazy.dt2ts("2021/08/28 08:48:05.451271")# 1630140485.451271print(res):link: Back to IndexDatab64encodeb64decodePlazy version: 0.1.3+Base64 encode and decode for string.plazy.b64encode(value: value to encode base64pretty: remove "=" character at the end after encoding. Default: False)plazy.b64decode(value: encoded base64 value to decode)importplazyif__name__=="__main__":encoded_val=plazy.b64encode('plazy')# cGxhenk=encoded_val=plazy.b64encode('plazy',pretty=True)# cGxhenk => Note: this string cannot be decoded!original_val=plazy.b64decode('cGxhenk=')# plazy:link: Back to Indexis_numberPlazy version: 0.1.4+Check whether string is a numberplazy.is_number(s: string to check)importplazyif__name__=="__main__":is_number=plazy.is_number("1")# Trueis_number=plazy.is_number("0.234")# Trueis_number=plazy.is_number("-0.234")# Trueis_number=plazy.is_number("1e3")# Trueis_number=plazy.is_number("plazy")# Falseis_number=plazy.is_number("1.23k9")# Falseis_number=plazy.is_number("x.3253254")# False:link: Back to IndexuniquePlazy version: 0.1.3+Turn list or tuple into unique list/tuple, keep order or sort the list/tuple.plazy.unique(seq: sequence to process. Eg: [1, 3, 1, 2], (2, 5, 5, 1, 2), ...sort: Sort result. Default: Falsereverse: Reverse result. Default: False)importplazyif__name__=="__main__":unique_t=plazy.unique(seq=(7,3,5,3,3,7,9))# -> (7, 3, 5, 9)unique_l=plazy.unique(seq=[7,3,5,3,3,7,9])# -> [7, 3, 5, 9]unique_rt=plazy.unique(seq=(7,3,5,3,3,7,9),sort=True,reverse=True)# -> (9, 7, 5, 3):link: Back to IndexFileread_txtPlazy version:0.1.2+, 0.1.4+Read lines of text file, eliminate redundant characters of each line, skip the empty lines.Read lines of text file as a list.plazy.read_txt(path: path to text fileline_func: function to process each line. Default: Noneskip_empty_line: skip empty line. Default: False)importplazyif__name__=="__main__":lines=plazy.read_txt(path='/home/video-list.txt')print(lines)# ['<line#1>', '<line#2>', '<line#3>', ...]# strip every text line, remove empty line in the list:lines=plazy.read_txt(path='/home/video-list.txt',line_func=lambdax:x.strip(),skip_empty_line=True)# -------------------------------# deprecated @ Plazy v0.1.2# lines = plazy.read_txt(path='/home/video-list.txt', strip=True)# print(lines) # ['<line#1>', '<line#2>', '<line#3>', ...]# lines = plazy.read_txt(path='/home/video-list.txt', strip=False) # no stripping:link: Back to Indexwrite_txtPlazy version: 0.1.4+Write text file.plazy.write_txt(path: path to text filelines: lines to writemode: write mode. Default: "w"cat_str: concat string between lines. Default: "\n" (new line character))importosimportplazyif__name__=="__main__":path='/home/plazy.txt'lines=["hello","world",]plazy.write_txt(path=path,lines=lines)assertos.path.isfile(path):link: Back to Indexlist_filesPlazy version: 0.1.1+List files recursively in directory.plazy.list_files(root: directory to traverse files. Default: "./" (current directory)filter_func: filter function to apply. Default: Noneis_include_root: include root directory path in the result. Default: False)importplazyif__name__=="__main__":files=plazy.list_files(root='images',filter_func=lambdax:Trueifx.endswith('.jpg')elseFalse,is_include_root=False)print(files)# ['1.jpg', '2.jpg', '_sub_/4.jpg']:link: Back to IndexCONTRIBUTINGStep 1. Fork ondevbranch.Step 2. Installpre-commiton the local dev environment.pip install pre-commit
pre-commit installStep 3. Write test case(s) for the new feature or the bug.Step 4. Write code to pass the tests.Step 5. Make sure that the new code passes all the pre-commmit conditions.pre-commit run -aStep 6. Create pull request.