Don Question
Don Question

Reputation: 11624

python's function-attributes: getting a list/dict of all assigned attributes

Out of pure curiosity: Is there an easy way (not more then two lines of code) to access the dictionary/list of assigned attributes of a function (from within that function)?

e.g.:

def func(*args):
    print("# of arguments = {0} ".format(len(args)))       # normal arguments
    print("# of attributes = {0}".format(len(func_attrs))) # function-attributes

func()

func.func_attr_1 = 'How do i get all attributes from within the associated function?'
func.func_attr_2 = 'How do i get all attributes from within the associated function?'

Since functions are callable objects it's possible to provide them with attributes, but there doesn't seem to bee a way to access a list of these attributes in an easy way.

locals() and globals() weren't helpful. dir() seems to do the trick, BUT you have to filter your attributes. Thats's somewhat inconvenient if you don't know the attribute-name in advance.

If i can assign an attribute there must .. should be a way to access their directory from within.

UPDATE:

i totaly forgot to actually call/invoke = instantiate the function before trying to access the attributes. ... my bad! - sry and thx for the answers ;-)

naturally i tried func.__dict__ and dir(func), but just didn't instantiate the function-object before doing so ... and in my original test i initially defined a attribute from within the function, then didn't call the function, but tried to access the function-attribute from the outer-scope - which naturally failed!

Upvotes: 2

Views: 206

Answers (3)

DSM
DSM

Reputation: 353489

Instead of using func.__dict__, I think it looks nicer to use vars():

>>> def func():
...     pass
... 
>>> func.a = 19
>>> 
>>> func.__dict__
{'a': 19}
>>> vars(func)
{'a': 19}
>>> vars(func) is func.__dict__
True

Fewer underscores.

Upvotes: 5

kindall
kindall

Reputation: 184385

Given the function name func, func.__dict__ is the function's dictionary, which contains all the attributes assigned directly on the function. You can then do membership testing (if foo in func.__dict__), iterate over the keys of the dictionary using for, or use other methods of dictionaries.

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

you means something like this, using __dict__:

In [11]: def foo():
   ....:     foo=1

In [12]: foo.bar=3

In [13]: foo.__dict__
Out[13]: {'bar': 3}

Upvotes: 5

Related Questions