Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.
My initial approach is to use a helper function as follows:
def deep_print_helper(file_path, line_sep):
with open(file_path) as f:
text = f.read()
return deep_print(text, line_sep)
def deep_print(s, line_sep):
lines = s.split(line_sep)
for l in lines:
if l.endswith('.txt'):
deep_print_helper(l, line_sep)
else:
print(l)
But having to pass line_sep
to the helper function only to pass it back again seems inelegant.
So I tried an approach that uses only one function:
def deep_print(line_sep, s='', file_path=''):
if file_path:
with open(file_path) as f:
s = f.read()
lines = s.split(line_sep)
for l in lines:
if l.endswith('.txt'):
deep_print(line_sep, file_path=l)
else:
print(l)
This has an implicit required argument (either s
or file_path
but not both), but since the user of the function will only use one form (s=
) it may not be too kludgey. It also seems a little odd from a user's perspective that line_sep
is the first argument.
Which approach is a better design? Is there another approach I should consider?