Created
April 6, 2018 03:31
-
-
Save cmattoon/c149f1abcb6df380ca2281a5e85dd1ee to your computer and use it in GitHub Desktop.
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
""" | |
Allows one to handle *args and **kwargs together in an intuitive way: | |
api.create_thing('my-thing', 'property-1', 'property-2') | |
or | |
api.create_thing('my-thing', prop2='property-2') | |
or | |
api.create_thing(**config) | |
>>> def myfunc(*args, **kwargs): | |
... argv = ARGV(args, kwargs) | |
... return argv.get(0, 'foo', 'FOO') | |
... | |
>>> myfunc('bar') | |
'bar' | |
>>> myfunc(foo='baz') | |
'baz' | |
>>> myfunc(bar='baz') | |
'FOO' | |
>>> myfunc() | |
'FOO' | |
""" | |
class ARGV: | |
def __init__(self, args, kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
self.argc = len(args) + len(kwargs) | |
def arg(self, idx, default=None): | |
try: | |
return self.args[idx] | |
except IndexError: | |
return default | |
def kwarg(self, key, default=None): | |
try: | |
return self.kwargs[key] | |
except KeyError: | |
return default | |
def get(self, idx, key=None, default=None): | |
""" | |
Looks for an arg at an index, or a fallback kwarg. | |
Returns `default` if neither is found | |
""" | |
try: | |
return self.args[idx] | |
except IndexError: | |
try: | |
return self.kwargs[key] | |
except KeyError: | |
return default | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment