Add attributes to function in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Raviexact
    New Member
    • Mar 2014
    • 5

    Add attributes to function in python

    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 ?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You can add attributes and associated values to function objects.
    Code:
    >>> def test():
    ... 	print 'test'
    ... 	
    >>> setattr(test, 'menu', 'bill')
    >>> test.menu
    'bill'
    I am wondering if function default arguments are what you really want.
    Code:
    >>> def test(name="Test Menu", default=True):
    ... 	if default is True:
    ... 		print "Name of menu: %s" % (name)
    ... 		
    >>> test()
    Name of menu: Test Menu
    >>>

    Comment

    Working...