[Python-ideas] Access to function objects
David Townshend
aquavitae69 at gmail.com
Sat Aug 6 10:10:06 CEST 2011
Has anyone else ever thought that it might be useful to access a function
object from within the call? I've come across this situation a few times
recently, and thought it would be very useful to be able to do something
like, for example:
def a_function() as func:
print(func.__doc__)
It would be useful, for example, to record state between calls, or if the
function wants to reuse its own properties (like in the above example).
Consider a function which should print the number of times it has been
called on every call
def counter(add) as func:
if not hasattr(func, 'count'):
func.count = 0
func.count += 1
print(func.count)
This could also be implemented using classes, i.e.
class Counter:
def __call__(self, add):
if not hasattr(func, 'count'):
func.count = 0
func.count += 1
print(func.count)
counter = Counter()
But this is much more clumsy, results in an extra object (the Counter class)
and will be quite complicated if counter is a method rather than a function.
The reason I've used "as" syntax is that it is consistent with other python
statements (e.g. "with" and "except"), wouldn't require a new keyword and is
backwardly compatible.
Any thoughts?
David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110806/98814859/attachment.html>
More information about the Python-ideas
mailing list