Python Introspection: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 13: Line 13:


<code>[[Python_Language#inspect|inspect]]</code> is a Standard Library module.
<code>[[Python_Language#inspect|inspect]]</code> is a Standard Library module.
====<tt>getmembers()</tt>====
<code>getmembers()</code> returns all members of an object as (name, value) pairs sorted by name. The object can be a module, class, etc. A predicate can be provided to the function, and the function returns only return members that satisfy a given predicate.
Example:
<syntaxhighlight lang='py'>
import inspect
modules = sys.modules.copy()
module = modules['some_package.some_subpackage.SomeClass']
class_tuples = inspect.getmembers(module, inspect.isclass)
for ct in class_tuples:
  print('class name: ', ct[0])
  print('class: ', ct[1])
</syntaxhighlight>


=Module Introspection=
=Module Introspection=

Revision as of 18:42, 8 July 2022

Internal

TODO

https://www.geeksforgeeks.org/code-introspection-in-python/

Overview

Introspection is Python's equivalent for Java reflection. It is the ability to determine the type of an object at runtime and to dynamically examine Python objects.

getattr()

getattr() is a built-in function that returns the value of the specified attribute from the specified object.

The inspect Standard Library Module

https://docs.python.org/3/library/inspect.html#module-inspect

inspect is a Standard Library module.

getmembers()

getmembers() returns all members of an object as (name, value) pairs sorted by name. The object can be a module, class, etc. A predicate can be provided to the function, and the function returns only return members that satisfy a given predicate.

Example:

import inspect

modules = sys.modules.copy()
module = modules['some_package.some_subpackage.SomeClass']
class_tuples = inspect.getmembers(module, inspect.isclass)
for ct in class_tuples:
  print('class name: ', ct[0])
  print('class: ', ct[1])

Module Introspection

Also see:

Python Language Modularization

Class Instance Introspection

Invoking a Static Method Dynamically