Say you have a piece of code that accepts either a list or a file name, and must filter through each item of either one provided by applying the same criteria:
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required = True)
group.add_argument('-n', '--name', help = 'single name', action = 'append')
group.add_argument('-N', '--names', help = 'text file of names')
args = parser.parse_args()
results = []
if args.name:
# We are dealing with a list.
for name in args.name:
name = name.strip().lower()
if name not in results and len(name) > 6: results.append(name)
else:
# We are dealing with a file name.
with open(args.names) as f:
for name in f:
name = name.strip().lower()
if name not in results and len(name) > 6: results.append(name)
I'd like to remove as much redundancy as possible in the above code. I tried creating the following function for strip
and lower
, but it didn't remove much repeat code:
def getFilteredName(name):
return name.strip().lower()
Is there any way to iterate over both a list and a file in the same function? How should I go about reducing as much code as possible?