I'm messing around with * and **, and figuring out what the use-cases of these operators would be. For this "study", I wrote a function scandir_and_execute
that traverses a directory (recursive by default) and executes a function exec_func
on each file that is encountered. The function is variable, meaning when calling scandir_and_execute
the programmer can indicate which function to run on every file. In addition, to figure out *
, I added a func_args
variable (defaults to an empty list) that can hold any number of argument.
The idea is that the programmer can use any exec_func
that they have defined (or built-in) to which the file is the first argument, and that they provide the needed arguments themselves, in a list, which is then expanded on the exec_func
call.
Note: at least Python 3.5 is required to run this function.
import os
def scandir_and_execute(root, exec_func, func_args=[], recursive=True, verbose=False):
if verbose:
print(f"TRAVERSING {root}")
# Use scandir to return iterator rather than list
for entry in os.scandir(root):
if entry.is_dir() and not entry.name.startswith('.'):
if recursive:
scan_and_execute(entry.path, exec_func, func_args, True, verbose)
elif entry.is_file():
if verbose:
print(f"\tProcessing {entry.name}")
# Unpack (splat) argument list, i.e. turn func_args into separate arguments and run exec_func
exec_func(entry.path, *func_args)
Is this the correct way to use *
, or am I misinterpreting the documentation and the concept of the operator? The function works, as far as I have tested it, but perhaps there are some caveats or non-pythonic things that I did? For instance, would it be better to write the function like this where the unnamed "superfluous" arguments are tupled together (or another way)?
def scandir_and_execute(root, exec_func, recursive=True, verbose=False, *func_args):