1

Today I found that I can assign attribute to function, but when I tried to assign the attribute inside itself, I failed:

>>> def a():
...     pass
...
>>> a.x = 1
>>> a.x
1
>>> def b():
...     b.x = 2
...
>>> b.x
AttributeError: 'function' object has no attribute 'x'

Is there a way to assign attribute to a function inside himself?

If there isn't, what's the usage of a function's attribute?

Zen
  • 3,775
  • 4
  • 25
  • 52

2 Answers2

2

The body of a function is not evaluated until the function is actually called; b.x in your example does not exist until b has been called at least once.

One use is to simulate C-style static variables, whose values persist between calls to the function. A trivial example counts how many times the function has been called.

def f():
    f.count += 1
    print "Call number {0}".format(count)
f.count = 0

Note that there is no problem assigning to f.count from inside count, but the initial assignment must occur after f is defined, since f does not exist until then.

chepner
  • 446,329
  • 63
  • 468
  • 610
  • What's the usage of function attribute? – Zen Apr 22 '14 at 03:39
  • I think there is an exception, I can assign __doc__ attribute inside a function itself, and can get it just like in the 'b.x' way I've mentioned above. – Zen Apr 22 '14 at 03:59
  • The difference is that `__doc__` (along with some other attributes) is predefined by the `def` statement itself. – chepner Apr 22 '14 at 04:09
1

Check out pep-0232. And this question here

Community
  • 1
  • 1
fr1tz
  • 7,402
  • 1
  • 11
  • 8