Argument parsing with python decorators
I was wondering if it's possible to wrap some class methods with a decorator that parses the arguments before sending it to the function. for example:
class integer(int):
def __init__(self, value=0)
self.value = value
for m in ['__add__','__sub__','__mul__']:#and so on
method = getattr(self, m)
method = magic_decorator(method)
...
given that magic_decorator would be a class or function that captures the single argument from these methods and parse than, for example if it would be a string, instead of letting it in to throw an exception, try to parse as a integer with int first.
That would be gre开发者_运维百科at for creating even more pythonic types from the native ones. If it's not possible to do in this stylish way, I would have to override each one doing a repetitive job on each one, which wouldn't be pythonic.
EDIT: "string"-object or integer-object wouldn't work even so, i would love to know how do I work around this. =]
I didn't a exhaustive search for duplicates, but I'm quite sure that isn't one 'cause my question is a little bit too specific.
Sorry for my bad English, I hope you understand, thanks in advance.
def magic_decorator(method):
def fun(self, arg):
if (type(arg) == str):
arg = int(arg)
return getattr(int, method)(self, arg)
return fun
class integer(int):
pass
for m in ['__add__','__sub__','__mul__']:
setattr(integer, m, magic_decorator(m))
i = integer(5)
i + "5"
Note: if you want the result to be integer
, use:
return integer(getattr(int, method)(self, arg))
Yes it is possible. Just overwrite every method. But be careful, decorators are slowing things dowwwwn.
You can just overwrite every method:
class new_integer(int):
__add__ = magic_decorator(int.__add__)
__sub__ = magic_decorator(int.__sub__)
...
Or you can do it the easy way:
class new_integer(int):
to_decorate = ( '__add__', '__sub__', ...)
for k in to_decorate:
locals()[k] = magic_decorator(getattr(int, k))
del to_decorate, k
精彩评论