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