Search code examples
pythonfunctionfunctools

How to set function properties/attributes from within the function definition?


How to set function properties/attributes from within the function definition?

For example is there a way to achieve this from within the function definition:

def test():
    pass

test.order = 1

So something along the lines of:

def test():
    self.order = 1
    pass

print(test.order)

Solution

  • In python, function is also an object, so of course you can set attributes of a function.

    But the function's attributes are not related to function's logic, so you may want to define them outside the function. decorator might be a good choice.

    def function_mark(**kwargs):
        def decoractor(func):
            func._my_info = kwargs
            return func
        return decoractor
    
    @function_mark(order=1)
    def test():
        pass
    
    print(test._my_info)