lsst.utils  15.0-6-g958ce35
get_caller_name.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 #
4 # Copyright 2008-2017 AURA/LSST.
5 #
6 # This product includes software developed by the
7 # LSST Project (http://www.lsst.org/).
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the LSST License Statement and
20 # the GNU General Public License along with this program. If not,
21 # see <https://www.lsstcorp.org/LegalNotices/>.
22 #
23 from __future__ import absolute_import, division, print_function
24 import inspect
25 
26 __all__ = ["get_caller_name"]
27 
28 
29 def get_caller_name(skip=2):
30  """Get the name of the caller method.
31 
32  Any item that cannot be determined (or is not relevant, e.g. a free
33  function has no class) is silently omitted, along with an
34  associated separator.
35 
36  Parameters
37  ----------
38  skip : `int`
39  How many levels of stack to skip while getting caller name;
40  1 means "who calls me", 2 means "who calls my caller", etc.
41 
42  Returns
43  -------
44  name : `str`
45  Name of the caller as a string in the form ``module.class.method``.
46  An empty string is returned if ``skip`` exceeds the stack height.
47 
48  Notes
49  -----
50  Adapted from from http://stackoverflow.com/a/9812105
51  by adding support to get the class from ``parentframe.f_locals['cls']``
52  """
53  stack = inspect.stack()
54  start = 0 + skip
55  if len(stack) < start + 1:
56  return ''
57  parentframe = stack[start][0]
58 
59  name = []
60  module = inspect.getmodule(parentframe)
61  if module:
62  name.append(module.__name__)
63  # add class name, if any
64  if 'self' in parentframe.f_locals:
65  name.append(type(parentframe.f_locals['self']).__name__)
66  elif 'cls' in parentframe.f_locals:
67  name.append(parentframe.f_locals['cls'].__name__)
68  codename = parentframe.f_code.co_name
69  if codename != '<module>': # top level usually
70  name.append(codename) # function or a method
71  return ".".join(name)