Created
July 25, 2017 06:45
-
-
Save frasertweedale/a9526901cbb4ce44f8dec845cd24fc2f to your computer and use it in GitHub Desktop.
optparse 'constructor' option demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from copy import copy | |
| from optparse import Option, OptionParser, OptionValueError | |
| class Stars(object): | |
| def __init__(self, stars): | |
| stars = float(stars) | |
| if stars < 0.5 or stars > 5 or stars % 0.5 != 0: | |
| raise ValueError( | |
| "Stars must be a whole or half number between 0.5 and 5") | |
| self.stars = stars | |
| def __str__(self): | |
| return "{} stars!".format(self.stars) | |
| def check_constructor(option, opt, value): | |
| con = option.constructor | |
| assert con is not None, "Oops! Developer forgot to set 'constructor' kwarg" | |
| try: | |
| return con(value) | |
| except Exception as e: | |
| raise OptionValueError("option {} invalid: {}".format(opt, e)) | |
| class MyOption(Option): | |
| ATTRS = Option.ATTRS + ["constructor"] | |
| TYPES = Option.TYPES + ("constructor",) | |
| TYPE_CHECKER = copy(Option.TYPE_CHECKER) | |
| TYPE_CHECKER["constructor"] = check_constructor | |
| parser = OptionParser(option_class=MyOption) | |
| opt = parser.add_option( | |
| "--rating", | |
| type='constructor', | |
| constructor=Stars, | |
| ) | |
| print parser.parse_args(['--rating=3'])[0].rating | |
| print parser.parse_args(['--rating=0.5'])[0].rating | |
| print parser.parse_args(['--rating=0.6'])[0].rating |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment