Skip to content

Instantly share code, notes, and snippets.

@gloryofrobots
Created July 20, 2018 12:51
Show Gist options
  • Save gloryofrobots/bc21143f9901ae02c308a6640ad2921f to your computer and use it in GitHub Desktop.
Save gloryofrobots/bc21143f9901ae02c308a6640ad2921f to your computer and use it in GitHub Desktop.
import argparse
class Value(object):
def __init__(self, alias, name):
super(Value, self).__init__()
self.alias = alias
self.name = name
class Converter(object):
def __init__(self, first, second, multiplier):
super(Converter, self).__init__()
self.first = first
self.second = second
self.multiplier = multiplier
def alias(self):
return "%s-%s" % (self.first.alias, self.second.alias)
def help(self):
return "convert 1 %s to %f %s" % (self.first.name, self.multiplier, self.second.name)
def info(self):
return "%s %s to %s" % (self.alias(), self.first.name, self.second.name)
def convert(self, value):
return value * self.multiplier
ML = Value("ml", "millimeter")
SM = Value("cm", "centimeter")
M = Value("m", "meter")
KM = Value("km", "kilometer")
class Converters:
def __init__(self):
self.converters = {}
self.add_converter(ML, SM, 10)
self.add_converter(ML, M, 1000)
self.add_converter(ML, KM, 100000)
self.add_converter(SM, KM, 10000)
self.add_converter(SM, M, 100)
self.add_converter(M, KM, 1000)
def add_converter(self, val1, val2, mult):
alias1 = "%s-%s" % (val1, val2)
alias2 = "%s-%s" % (val2, val1)
self.converters[alias1] = Converter(val1, val2, 1.0/float(mult))
self.converters[alias2] = Converter(val2, val1, mult)
def __iter__(self):
def sort(c):
return c.alias()
return sorted(self.converters.values(), key=sort).__iter__()
def info(self, joiner="\n "):
result = []
for c in self:
result.append(c.info())
return joiner.join(result)
def action(converter):
class Action(argparse.Action):
def __init__(self, option_strings, dest, nargs, **kwargs):
super(Action, self).__init__(option_strings, dest, nargs, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
# result = [converter.convert(val) for val in values]
if not isinstance(values, list):
values = [values]
result = [converter.convert(val) for val in values]
setattr(namespace, "result", result)
return Action
def main():
converters = Converters()
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--list", help="show converter list", action="store_true")
for c in converters:
parser.add_argument("-" + c.alias(), nargs="*", help=c.help(), action=action(c), type=float)
args = parser.parse_args()
if args.list:
print "Available converters:\n %s" % converters.info()
else:
try:
if args.result:
print " ".join(map(str, args.result))
except AttributeError:
parser.print_help()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment