find_current_module

astropy.utils.introspection.find_current_module(depth=1, finddiff=False)[source]

Determines the module/package from which this function is called.

This function has two modes, determined by the finddiff option. it will either simply go the requested number of frames up the call stack (if finddiff is False), or it will go up the call stack until it reaches a module that is not in a specified set.

Parameters:
depthpython:int

Specifies how far back to go in the call stack (0-indexed, so that passing in 0 gives back astropy.utils.misc).

finddiffbool or python:list

If False, the returned mod will just be depth frames up from the current frame. Otherwise, the function will start at a frame depth up from current, and continue up the call stack to the first module that is different from those in the provided list. In this case, finddiff can be a list of modules or modules names. Alternatively, it can be True, which will use the module depth call stack frames up as the module the returned module most be different from.

Returns:
modpython:module or python:None

The module object or None if the package cannot be found. The name of the module is available as the __name__ attribute of the returned object (if it isn’t None).

Raises:
ValueError

If finddiff is a list with an invalid entry.

Examples

The examples below assume that there are two modules in a package named pkg. mod1.py:

def find1():
    from astropy.utils import find_current_module
    print find_current_module(1).__name__
def find2():
    from astropy.utils import find_current_module
    cmod = find_current_module(2)
    if cmod is None:
        print 'None'
    else:
        print cmod.__name__
def find_diff():
    from astropy.utils import find_current_module
    print find_current_module(0,True).__name__

mod2.py:

def find():
    from .mod1 import find2
    find2()

With these modules in place, the following occurs:

>>> from pkg import mod1, mod2
>>> from astropy.utils import find_current_module
>>> mod1.find1()
pkg.mod1
>>> mod1.find2()
None
>>> mod2.find()
pkg.mod2
>>> find_current_module(0)
<module 'astropy.utils.misc' from 'astropy/utils/misc.py'>
>>> mod1.find_diff()
pkg.mod1