Added in_callback() to hooke.util.callback and pulled out is_iterable().
[hooke.git] / hooke / util / caller.py
1 # Copyright
2
3 """Define :func:`caller_name`.
4
5 This is useful, for example, to declare the `@callback` decorator for
6 making GUI writing less tedious.  See :mod:`hooke.util.callback` and
7 :mod:`hooke.ui.gui` for examples.
8 """
9
10 import sys
11
12
13 def frame(depth=1):
14     """Return the frame for the function `depth` up the call stack.
15
16     Notes
17     -----
18     The `ZeroDivisionError` trick is from stdlib's traceback.py.  See
19     the Python Refrence Manual on `traceback objects`_ and `frame
20     objects`_.
21
22     .. _traceback objects:
23       http://docs.python.org/reference/datamodel.html#index-873
24     .. _frame objects:
25       http://docs.python.org/reference/datamodel.html#index-870
26     """
27     try:
28         raise ZeroDivisionError
29     except ZeroDivisionError:
30         traceback = sys.exc_info()[2]
31     f = traceback.tb_frame
32     for i in range(depth):
33         f = f.f_back
34     return f
35
36 def caller_name(depth=1):
37     """Return the name of the function `depth` up the call stack.
38
39     Examples
40     --------
41
42     >>> def x(depth):
43     ...     y(depth)
44     >>> def y(depth):
45     ...     print caller_name(depth)
46     >>> x(1)
47     y
48     >>> x(2)
49     x
50     >>> x(0)
51     caller_name
52
53     Notes
54     -----
55     See the Python Refrence manual on `frame objects`_ and
56     `code objects`_.
57
58     .. _frame objects:
59       http://docs.python.org/reference/datamodel.html#index-870
60     .. _code objects:
61       http://docs.python.org/reference/datamodel.html#index-866
62     """
63     f = frame(depth=depth+1)
64     return f.f_code.co_name