Search code examples
pythonpython-decorators

Is it pythonic to apply decorator to __init__ function?


Came across the need to do some sanity check of __init__() args. We'd like to move this sanity-checking logic into decorator.

I did some prototyping, it seems applying decorator to __init__() does work:

def my_dec(func):
    def wrapper(*args, **kwargs):
        print('a')
        func(*args, **kwargs)
    return wrapper

class testClass(object):
    @my_dec
    def __init__(self):
        print('b')

Having a decorator above __init__ seems to be slightly messy. But besides that, is there any downside to this? Anything non-pythnoic?


Solution

  • I think "pythonic" here may be subjective (And I use may lightly) but I believe keeping to the more standard approach and doing sanity checks within __init__ and keep the guessing to a minimum later on in debugging or when working with a team.

    Something like this seems to do the same thing but feel more natural and is easier to follow.

    def sanity_check():
        print('a')
        #do checks here
        return True #or False
    
    class testClass(object):
    
        def __init__(self):
            if sanity_check():
                print('b')