0

In Python functions (function objects) can have attributes.

For example:

def func(a):
    return a*a

func.attr = 1

Is there is a way to see this attribute and its value?

I have tried inspect.getfullargspec from inspect module but it shows only function arguments.

FullArgSpec(args=['a'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={})
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    `getfullargspec` is to get the *full* *arg*ument *spec*ification, the parameters the function expects. If you want to see *attributes*, try e.g. `dir`. – jonrsharpe Dec 25 '20 at 13:02

2 Answers2

2

Just like any other object, you can use vars:

def func(a):
    return a*a

func.attr = 1

print(vars(func))
# {'attr': 1}
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

Python vars() function can be used here to get the entire object

Code

def func(a):
    return a**3

func.function = "Cubic Function"
func.arguments = "Integers"

print(func(99))

print(vars(func))

print(vars(func)["function"])

print(vars(func)["arguments"])

OUTPUT

970299
{'function': 'Cubic Function', 'arguments': 'Integers'}
Cubic Function
Integers
Ayush
  • 457
  • 8
  • 16