Skip to content

inspect_utils

Utilities for inspecting Python objects, classes, functions, and frames.

This module provides helper functions for runtime introspection, including qualified name resolution, caller frame inspection, argument extraction from locals, class slot enumeration, and MRO traversal.

Main APIs

classof, moduleof, cname, func_name, qual_name, qual_mro, is_subclass, get_caller_function, current_module, fetch_args, fetch_call, get_fn_kwargs, get_defaulted_params, parent_locals, parent_globals, parent_coords, class_slots

Note that the parent_*() helpers look past the immediate caller: the frame at level + 2 - i.e. the caller of the function calling the helper - is inspected by default.

Example
from py_misc_utils import inspect_utils as iu

class Greeter:

  def hello(self):
    pass

# Qualified names resolve through instances to their class.
assert iu.qual_name(Greeter()).endswith('.Greeter')
assert iu.qual_name(dict) == 'builtins.dict'

classof(obj)

Returns the class of an object, or the object itself if it is a class.

Parameters:

Name Type Description Default
obj

An object or class.

required

Returns:

Type Description

obj if it is a class, otherwise obj.__class__ or None if

unavailable.

Source code in py_misc_utils/inspect_utils.py
41
42
43
44
45
46
47
48
49
50
51
def classof(obj):
  """Returns the class of an object, or the object itself if it is a class.

  Args:
    obj: An object or class.

  Returns:
    ``obj`` if it is a class, otherwise ``obj.__class__`` or None if
    unavailable.
  """
  return obj if inspect.isclass(obj) else getattr(obj, '__class__', None)

moduleof(obj)

Returns the module name where an object's class is defined.

Parameters:

Name Type Description Default
obj

An object or class.

required

Returns:

Type Description

The __module__ attribute of the object's class, or None if not

available.

Source code in py_misc_utils/inspect_utils.py
54
55
56
57
58
59
60
61
62
63
64
65
66
def moduleof(obj):
  """Returns the module name where an object's class is defined.

  Args:
    obj: An object or class.

  Returns:
    The ``__module__`` attribute of the object's class, or None if not
    available.
  """
  cls = classof(obj)

  return getattr(cls, '__module__', None) if cls is not None else None

cname(obj)

Returns the class name of an object.

Parameters:

Name Type Description Default
obj

An object or class.

required

Returns:

Type Description

The __name__ attribute of the object's class, or None if not

available.

Source code in py_misc_utils/inspect_utils.py
69
70
71
72
73
74
75
76
77
78
79
80
81
def cname(obj):
  """Returns the class name of an object.

  Args:
    obj: An object or class.

  Returns:
    The ``__name__`` attribute of the object's class, or None if not
    available.
  """
  cls = classof(obj)

  return cls.__name__ if cls is not None else None

func_name(func)

Returns the name of a function or class.

Parameters:

Name Type Description Default
func

A function, method, class, or other callable object.

required

Returns:

Type Description

The __name__ attribute if available, otherwise the class name via

cname(func).

Source code in py_misc_utils/inspect_utils.py
84
85
86
87
88
89
90
91
92
93
94
95
96
def func_name(func):
  """Returns the name of a function or class.

  Args:
    func: A function, method, class, or other callable object.

  Returns:
    The ``__name__`` attribute if available, otherwise the class name via
    ``cname(func)``.
  """
  fname = getattr(func, '__name__', None)

  return fname if fname is not None else cname(func)

qual_name(obj, builtin_strip=False)

Returns the qualified name for a class, function, method, or module.

For non-class/function/method/module objects, uses the object's class - so the qualified name of an instance is the qualified name of its class.

Parameters:

Name Type Description Default
obj

The object to get the qualified name for.

required
builtin_strip

If True, strips builtin module prefixes.

False

Returns:

Type Description

A dotted qualified name string.

Source code in py_misc_utils/inspect_utils.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def qual_name(obj, builtin_strip=False):
  """Returns the qualified name for a class, function, method, or module.

  For non-class/function/method/module objects, uses the object's class -
  so the qualified name of an instance is the qualified name of its class.

  Args:
    obj: The object to get the qualified name for.
    builtin_strip: If True, strips builtin module prefixes.

  Returns:
    A dotted qualified name string.
  """
  if (inspect.isclass(obj) or inspect.isroutine(obj) or inspect.ismodule(obj)):
    ref = obj
  else:
    ref = obj.__class__

  return _qual_name(ref, builtin_strip=builtin_strip)

qual_mro(obj, builtin_strip=False)

Yields qualified names for all classes in an object's MRO.

Parameters:

Name Type Description Default
obj

A class or an instance of a class.

required
builtin_strip

If True, strips builtin module prefixes.

False

Yields:

Type Description

Qualified name strings for each class in cls.__mro__ - from the

most specific class up to object.

Source code in py_misc_utils/inspect_utils.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def qual_mro(obj, builtin_strip=False):
  """Yields qualified names for all classes in an object's MRO.

  Args:
    obj: A class or an instance of a class.
    builtin_strip: If True, strips builtin module prefixes.

  Yields:
    Qualified name strings for each class in ``cls.__mro__`` - from the
    most specific class up to ``object``.
  """
  cls = obj if inspect.isclass(obj) else obj.__class__

  for scls in cls.__mro__:
    yield _qual_name(scls, builtin_strip=builtin_strip)

is_subclass(cls, cls_group)

Checks whether cls is a subclass of cls_group.

Parameters:

Name Type Description Default
cls

The class to check.

required
cls_group

A class or tuple of classes to check against.

required

Returns:

Type Description

True if cls is a class and is a subclass of cls_group, False

otherwise.

Source code in py_misc_utils/inspect_utils.py
162
163
164
165
166
167
168
169
170
171
172
173
def is_subclass(cls, cls_group):
  """Checks whether cls is a subclass of cls_group.

  Args:
    cls: The class to check.
    cls_group: A class or tuple of classes to check against.

  Returns:
    True if ``cls`` is a class and is a subclass of ``cls_group``, False
    otherwise.
  """
  return inspect.isclass(cls) and issubclass(cls, cls_group)

get_caller_function(back=0, frame=None)

Returns the function object of the caller at a given stack depth.

Parameters:

Name Type Description Default
back

Number of frames to go back from the current frame (default 0).

0
frame

An optional frame object to use instead of walking the stack.

None

Returns:

Type Description

The function object of the caller, resolved via qualified name lookup.

Source code in py_misc_utils/inspect_utils.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def get_caller_function(back=0, frame=None):
  """Returns the function object of the caller at a given stack depth.

  Args:
    back: Number of frames to go back from the current frame (default 0).
    frame: An optional frame object to use instead of walking the stack.

  Returns:
    The function object of the caller, resolved via qualified name lookup.
  """
  if frame is None:
    frame = tb.get_frame(back + 1)

  return _fn_lookup(frame, frame.f_code.co_qualname)

current_module()

Returns the module of the caller's frame.

Returns:

Type Description

The module object of the frame one level up the call stack.

Source code in py_misc_utils/inspect_utils.py
225
226
227
228
229
230
231
def current_module():
  """Returns the module of the caller's frame.

  Returns:
    The module object of the frame one level up the call stack.
  """
  return inspect.getmodule(tb.get_frame(1))

fetch_args(func, locs, input_args=())

Extracts positional and keyword arguments for a function from locals.

Optional parameters pick their value from the matching local variable, falling back to the parameter default when the local is None or missing.

Parameters:

Name Type Description Default
func

The function whose signature is used to extract arguments.

required
locs

A dict-like mapping of local variable names to values.

required
input_args

A tuple of input arguments to use as positional defaults.

()

Returns:

Type Description

A tuple (args, kwargs) where args is a list of positional

arguments and kwargs is a dict of keyword arguments.

Raises:

Type Description
RuntimeError

If a required positional argument is missing from locals and no input_args remain.

Source code in py_misc_utils/inspect_utils.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def fetch_args(func, locs, input_args=()):
  """Extracts positional and keyword arguments for a function from locals.

  Optional parameters pick their value from the matching local variable,
  falling back to the parameter default when the local is None or
  missing.

  Args:
    func: The function whose signature is used to extract arguments.
    locs: A dict-like mapping of local variable names to values.
    input_args: A tuple of input arguments to use as positional defaults.

  Returns:
    A tuple ``(args, kwargs)`` where ``args`` is a list of positional
    arguments and ``kwargs`` is a dict of keyword arguments.

  Raises:
    RuntimeError: If a required positional argument is missing from locals
      and no input_args remain.
  """
  sig = inspect.signature(func)

  def args_append(args, n):
    """Append the value of a positional parameter to the arguments.

    Args:
      args: The list of positional arguments being built.
      n: The name of the parameter to append.
    """
    if len(args) < len(input_args):
      args.append(input_args[len(args)])
    else:
      pv = locs.get(n, _NONE)
      if pv is not _NONE:
        args.append(pv)
      else:
        alog.xraise(RuntimeError, f'Missing argument: {n}')

  def kwargs_assign(kwargs, n, p):
    """Assign the value of an optional parameter to the kwargs.

    Args:
      kwargs: The dict of keyword arguments being built.
      n: The name of the parameter to assign.
      p: The inspect.Parameter of the parameter.
    """
    pv = locs.get(n, _NONE)
    if pv is _NONE or (pv is None and p.default is not inspect.Signature.empty):
      pv = p.default
    if pv is not inspect.Signature.empty:
      kwargs[n] = pv

  args, kwargs = [], dict()
  for n, p in sig.parameters.items():
    if p.kind == p.POSITIONAL_ONLY:
      args_append(args, n)
    elif p.kind == p.POSITIONAL_OR_KEYWORD:
      if p.default is inspect.Signature.empty:
        args_append(args, n)
      else:
        kwargs_assign(kwargs, n, p)
    else:
      kwargs_assign(kwargs, n, p)

  return args, kwargs

fetch_call(func, locs, input_args=())

Calls a function with arguments extracted from locals.

Uses fetch_args() to build the call arguments from the given locals.

Parameters:

Name Type Description Default
func

The function to call.

required
locs

A dict-like mapping of local variable names to values.

required
input_args

A tuple of input arguments to use as positional defaults.

()

Returns:

Type Description

The result of calling func with the extracted arguments.

Source code in py_misc_utils/inspect_utils.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def fetch_call(func, locs, input_args=()):
  """Calls a function with arguments extracted from locals.

  Uses fetch_args() to build the call arguments from the given locals.

  Args:
    func: The function to call.
    locs: A dict-like mapping of local variable names to values.
    input_args: A tuple of input arguments to use as positional defaults.

  Returns:
    The result of calling ``func`` with the extracted arguments.
  """
  args, kwargs = fetch_args(func, locs, input_args=input_args)

  return func(*args, **kwargs)

get_fn_kwargs(args, func, prefix=None, roffset=None)

Extracts keyword arguments for a function from an args dict.

Uses inspect.getfullargspec to determine parameter names and defaults.

Parameters:

Name Type Description Default
args

A dict mapping argument names to values.

required
func

The function whose signature is used.

required
prefix

An optional prefix string for argument names (e.g. 'config.').

None
roffset

An offset index for required arguments.

None

Returns:

Type Description

A dict of parameter names to values, using defaults where available.

Source code in py_misc_utils/inspect_utils.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def get_fn_kwargs(args, func, prefix=None, roffset=None):
  """Extracts keyword arguments for a function from an args dict.

  Uses inspect.getfullargspec to determine parameter names and defaults.

  Args:
    args: A dict mapping argument names to values.
    func: The function whose signature is used.
    prefix: An optional prefix string for argument names (e.g. 'config.').
    roffset: An offset index for required arguments.

  Returns:
    A dict of parameter names to values, using defaults where available.
  """
  aspec = inspect.getfullargspec(func)

  sdefaults = aspec.defaults or ()
  sargs = aspec.args or ()
  ndelta = len(sargs) - len(sdefaults)

  fnargs = dict()
  for i, an in enumerate(sargs):
    if i != 0 or an != 'self':
      nn = f'{prefix}.{an}' if prefix else an
      di = i - ndelta
      if di >= 0:
        fnargs[an] = args.get(nn, sdefaults[di])
      elif roffset is not None and i >= roffset:
        aval = args.get(nn, _NONE)
        tas.check(aval is not _NONE,
                  msg=f'The "{an}" argument must be present as "{nn}": {args}')
        fnargs[an] = aval

  if aspec.kwonlyargs:
    for an in aspec.kwonlyargs:
      nn = f'{prefix}.{an}' if prefix else an
      aval = args.get(nn, aspec.kwonlydefaults.get(an, inspect.Signature.empty))
      if aval is not inspect.Signature.empty:
        fnargs[an] = aval

  return fnargs

get_defaulted_params(func)

Returns parameters of a function that have default values.

Parameters:

Name Type Description Default
func

The function to inspect.

required

Returns:

Type Description

A tuple of inspect.Parameter objects whose default is not empty.

Source code in py_misc_utils/inspect_utils.py
362
363
364
365
366
367
368
369
370
371
372
373
374
def get_defaulted_params(func):
  """Returns parameters of a function that have default values.

  Args:
    func: The function to inspect.

  Returns:
    A tuple of ``inspect.Parameter`` objects whose default is not empty.
  """
  sig = inspect.signature(func)

  return tuple(
      p for p in sig.parameters.values() if p.default is not inspect.Signature.empty)

parent_locals(level=0)

Returns the locals dict of a parent frame.

Parameters:

Name Type Description Default
level

Additional levels to go up (default 0 means the immediate caller's parent).

0

Returns:

Type Description

The f_locals dict of the frame at level + 2 up the stack.

Source code in py_misc_utils/inspect_utils.py
377
378
379
380
381
382
383
384
385
386
387
388
389
def parent_locals(level=0):
  """Returns the locals dict of a parent frame.

  Args:
    level: Additional levels to go up (default 0 means the immediate caller's
      parent).

  Returns:
    The ``f_locals`` dict of the frame at ``level + 2`` up the stack.
  """
  frame = tb.get_frame(level + 2)

  return frame.f_locals

parent_globals(level=0)

Returns the globals dict of a parent frame.

Parameters:

Name Type Description Default
level

Additional levels to go up (default 0 means the immediate caller's parent).

0

Returns:

Type Description

The f_globals dict of the frame at level + 2 up the stack.

Source code in py_misc_utils/inspect_utils.py
392
393
394
395
396
397
398
399
400
401
402
403
404
def parent_globals(level=0):
  """Returns the globals dict of a parent frame.

  Args:
    level: Additional levels to go up (default 0 means the immediate caller's
      parent).

  Returns:
    The ``f_globals`` dict of the frame at ``level + 2`` up the stack.
  """
  frame = tb.get_frame(level + 2)

  return frame.f_globals

parent_coords(level=0)

Returns the filename and line number of a parent frame.

Parameters:

Name Type Description Default
level

Additional levels to go up (default 0 means the immediate caller's parent).

0

Returns:

Type Description

A tuple (filename, lineno) for the frame at level + 2 up the stack.

Source code in py_misc_utils/inspect_utils.py
407
408
409
410
411
412
413
414
415
416
417
418
419
def parent_coords(level=0):
  """Returns the filename and line number of a parent frame.

  Args:
    level: Additional levels to go up (default 0 means the immediate caller's
      parent).

  Returns:
    A tuple ``(filename, lineno)`` for the frame at ``level + 2`` up the stack.
  """
  frame = tb.get_frame(level + 2)

  return frame.f_code.co_filename, frame.f_lineno

class_slots(cls)

Returns all slot names defined across a class's MRO.

Note that slot names reappear once per ancestor defining them: a slotless subclass does not hide the slots of its parents.

Parameters:

Name Type Description Default
cls

A class object.

required

Returns:

Type Description

A tuple of slot name strings from all classes in cls.__mro__ -

empty for classes without slots anywhere in their hierarchy.

Source code in py_misc_utils/inspect_utils.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def class_slots(cls):
  """Returns all slot names defined across a class's MRO.

  Note that slot names reappear once per ancestor defining them: a
  slotless subclass does not hide the __slots__ of its parents.

  Args:
    cls: A class object.

  Returns:
    A tuple of slot name strings from all classes in ``cls.__mro__`` -
    empty for classes without slots anywhere in their hierarchy.
  """
  slots = itertools.chain.from_iterable(
      getattr(mcls, '__slots__', []) for mcls in cls.__mro__)

  return tuple(slots)