Python/ManyArgs
From ProgrammingExamples
Programmers spend much programming time doing maintenance on existing code. This snippet shows one way to handle a function that just keeps growing (without refactoring the code that uses it) in a nice flexible way
import datetime
"""
How to easily deal with many parameters in maintenance
The problem:
- a function has grown to require many parameters, many with default values
- the function is being maintained (and param list likely will grow)
The forces:
- we want the defaults to be seen "all in one place" for self documentation
- we may need to handle old positional parameters, also self documented
- we want to allow the defaults to be defined outside the function def
- we want speed and clarity
The answer: Use a dictionary of defaults
"""
def handleManyArgs(root,logdir,auths,**kwargs):
# handle old positional parameters: Historic artifact
# opportunity to spell the names nicely, self-document meaning
kwargs["rootDirectory"] = root
kwargs['logDirectory'] = logdir
kwargs['authorizedUsers'] = auths
# this dictionary will probably be from a configuration file or similar
defaultArgs = {
'alpha': 0, # document this parameter
'beta': 'usually', # ditto
'gamma': 'ray', # ditto
'delta': 12, # etc
'epsilon': 1.03e-12,
'zeta': None,
'eta': datetime.time(hour=11,minute=12,second=13),
'theta': None,
'etc': 'many more',
}
for k,v in defaultArgs.items():
kwargs.setdefault(k,v)
print "All arguments:\n %s"%("\n ".join(["%s->%s"%(str(k),str(v)) for k,v in kwargs.items()]))
if __name__ == "__main__":
handleManyArgs("/","/tmp",['griswolf'])
handleManyArgs("/","/tmp",['griswolf','daviddoria'],gamma='mary',theta=1.35)