Hi,

I would like to add some descriptions to functions on top of every function

ex :

[Name = 'Test menu', Default=True, etc..]
def test():
pass

My actual scenario is , I create Menus dynamically by reading all methods from a module at run time.

So i don't want to take menu name as test, i want user to provide menu name on his wish in "Name" attribute of a function. There will be more attribute, not only Name.
Is there any possibility in python, please anyone guide me ?

Why not use a decorator ?

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

__doc__ = '''adding attributes to a function
'''

def menu_config(**attrs):
    def decorator(func):
        func.menu_attrs = attrs
        return func
    return decorator

@menu_config(Name = 'Test Menu', Default = True)
def test():
    print('foo')


if __name__ == '__main__':
    print(test.menu_attrs)

""" my output -->
{'Default': True, 'Name': 'Test Menu'}
"""

I would create a decorator, that decorates the function.

Something like:

@menu_item(Name="Save", enabled=True)
def save_menu():
    function body

The decorators would add a dictionary (for example with the name menu_data) to the decorated function with the arguments.

The program code would scan the functions and if a function has menu_data attribute, then it would use it. Or better the decorator would register it into an application wide user menu list.

Edited 2 Years Ago by slate

Comments
I was faster!
This article has been dead for over six months. Start a new discussion instead.