2

I have at work a framework (designed by a programmer which is considered the most experienced in our organization) that has the oddest structure I had ever seen. The framework has a lot of APIs, all with the same structure:

  • each API (function) has a 'self' argument, although it is a simple function (not a class method)
  • this 'self' argument is added inside the decorator @incself and is in fact a reference to the function itself
  • inside each function, all arguments are translated into attributes of the 'self' object (= attributes of the function)
  • then, throughout the function code, the arguments are used in the form self.arg1, self.arg2, ...

Since apparently I'm the only one thinking this is odd, please help me with your opinion. Did any of you used/saw a similar approach and what possible benefits could it have?

from functools import wraps

def incself(func):
    @wraps(func)
    def wrapper(*args, **kwds):
        return func(func, *args, **kwds)
    return wrapper

@incself
def apiFunc01(self, **kwargs):
    for key, value in kwargs.items():
        setattr(self, key, value)
    #....
    print('Connect to IP={0}, port={1}'.format(self.ip, self.port))
    #....

if __name__ == '__main__':
    # the API is called without the 'self' argument!!
    apiFunc01(ip='2.3.4.5', port=2345)

Thanks!

nicksorin
  • 23
  • 4
  • I think it is weird. What is the alleged benefit? _Explicit is better than implicit_ and all that – wim Jul 11 '14 at 13:13
  • What about recursive functions -- wouldn't a second invocation of the same function before the first one has returned overwrite the values of first? It also seems like a lot of additional overhead with no apparent benefit. – martineau Jul 11 '14 at 13:20

1 Answers1

0

It a way of remind the args of the last call:

>>>apiFunc01(ip='a', port=123)
Connect to IP=a, port=123

>>>apiFunc01()
Connect to IP=a, port=123

>>>apiFunc01(ip='2.3.4.5', port=123)
Connect to IP=2.3.4.5, port=123

>>>apiFunc01()
Connect to IP=2.3.4.5, port=123
Antoine
  • 1,070
  • 7
  • 11