0

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
  • 4,381
  • 5
  • 29
  • 56
  • "I failed:" Yes, for the same reason that, if the code inside `b()` said `print("hello")`, the code would not print `hello`. The code inside the function only runs when the function is called. `b.x = 2` is code inside the function. The function is not called, therefore the code does not run. This is elementary logical reasoning that has **nothing to do with** function attributes being special (they aren't particularly). – Karl Knechtel Jan 25 '23 at 21:29

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
  • 497,756
  • 71
  • 530
  • 681
  • 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
  • 8,018
  • 1
  • 12
  • 8