The function attribute do_something.n
is incremented each time you call the function.
It bothered me that I declared the attribute do_something.n=0
outside the function.
I answered the question Using queue.PriorityQueue, not caring about comparisons using a "function-attribute" to provide a unique counter for usage with PriorityQueue's - there is a nicer solution by MartijnPieters)
MCVE:
def do_something():
do_something.n += 1
return do_something.n
# need to declare do_something.n before usign it, else
# AttributeError: 'function' object has no attribute 'n'
# on first call of do_something() occures
do_something.n = 0
for _ in range(10):
print(do_something()) # prints 1 to 10
What other ways are there, to define the attribute of a function "inside" of it so you avoid the AttributeError: 'function' object has no attribute 'n'
if you forget it?
Edited plenty of other ways in from comments: