1 # Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with Hooke. If not, see <http://www.gnu.org/licenses/>.
18 """Define :func:`caller_name`.
20 This is useful, for example, to declare the `@callback` decorator for
21 making GUI writing less tedious. See :mod:`hooke.util.callback` and
22 :mod:`hooke.ui.gui` for examples.
29 """Return the frame for the function `depth` up the call stack.
33 The `ZeroDivisionError` trick is from stdlib's traceback.py. See
34 the Python Refrence Manual on `traceback objects`_ and `frame
37 .. _traceback objects:
38 http://docs.python.org/reference/datamodel.html#index-873
40 http://docs.python.org/reference/datamodel.html#index-870
43 raise ZeroDivisionError
44 except ZeroDivisionError:
45 traceback = sys.exc_info()[2]
46 f = traceback.tb_frame
47 for i in range(depth):
51 def caller_name(depth=1):
52 """Return the name of the function `depth` up the call stack.
60 ... print(caller_name(depth))
70 See the Python Refrence manual on `frame objects`_ and
74 http://docs.python.org/reference/datamodel.html#index-870
76 http://docs.python.org/reference/datamodel.html#index-866
78 f = frame(depth=depth+1)
79 return f.f_code.co_name
81 def caller_names(depth=1):
82 """Iterate through the names of all functions up the call stack.
92 ... print(list(caller_names()))
93 >>> x() # doctest: +ELLIPSIS
95 >>> y() # doctest: +ELLIPSIS
97 >>> z() # doctest: +ELLIPSIS
100 depth = 2 # start at caller_names()'s caller.
103 yield caller_name(depth=depth)
104 except AttributeError: