Decorators always interested me, dunno why, they seem such a metacoding sort of programming, but to understand one function simply, I need examples, not just theory, I dunno if you are on the same page on this. So, I finally get one simple example, all made by myself, that is simple to understand and also useful, cause it makes me know how much time a function takes to be executed so that I can eventually think to an alternative way to do the job in less time. This decorator can be used for any function, without having to modify the function, so it’s really reusable, it gives the truly meaning of the word reusable. So store it in your snippet folder to have it always at your disposal or create a module and put it in the path (file .pth in the path of your python.exe installation.
To find where your python.exe file is I do this method:
C:\Users\giova>py Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys,os >>> os.startfile(sys.path[4]) >>>
You will see the folder open at the right place
Here it is. You cans see the python.exe at the number 1 arrow and the modules.pth at arrow n.2.
Here is what is inside the modules.pth:
There is just the path where the modules are. Now you can import your modules like any installed modules or built-in module.
import os import time def timexec(func): def wrapper(): start = time.time() func() end = time.time() print(f"Time: {end - start} seconds") return wrapper @timexec def get_files_list() -> str: txt = "" for r, d, f in os.walk(os.getcwd()): r = r.replace("\\", "/") txt += f"{r}, \n\t, {f}" get_files_list()
A more refinished verion of the code
import os import time def timexec(func): def wrapper(): start = time.time() func() end = time.time() print(f"Time: {end - start} seconds") return wrapper @timexec def get_files_list() -> str: txt = "" for r, d, f in os.walk(os.getcwd()): txt += f"DIR:''{r}'':\n\tFOLDERS:{d} - FILES:{f}\n\n" print(txt) get_files_list()
Adding informations about files
Just because I like to add code to previous versions, here are some information about the number of files and the biggest folder in terms of number of files in it.
import os import time def timexec(func): def wrapper(): start = time.time() func() end = time.time() print(f"Time: {end - start} seconds") return wrapper @timexec def get_files_list() -> str: txt = "" countfile = 0 bignumber = 0 bigname = "" for r, d, f in os.walk(os.getcwd()): txt += f"DIR:''{r}'':\n\tFOLDERS:{d} - FILES:{f} - Num. file:{len(f)}\n\n" countfile += len(f) if len(f) > bignumber: bigname = r bignumber = len(f) print(txt) print(f"Num. File: {countfile}") print(f"Folder with more files: {bigname} files: {bignumber}") get_files_list()
Have fun.
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame