Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument parsing with python decorators

Tags:

python

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 great 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.

like image 806
BrainStorm Avatar asked Dec 12 '25 15:12

BrainStorm


1 Answers

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))
like image 166
Karoly Horvath Avatar answered Dec 14 '25 17:12

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!