Python Programming/Reflection

This is the current revision of this page, as edited by 2402:3a80:1c71:9699:1579:b450:423f:c3cf (discuss) at 05:59, 20 November 2022 (Isinstance: The comments (representing the results when the corresponding lines are executed) for the second last and the third last lines was not correct, when run in interpreter session (Python v3.10.2), hence, edited :). The present address (URL) is a permanent link to this version.

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


A Python script can find out about the type, class, attributes and methods of an object. This is referred to as reflection or introspection. See also Metaclasses.

Reflection-enabling functions include type(), isinstance(), callable(), dir() and getattr().

Type

edit

The type method enables to find out about the type of an object. The following tests return True:

  • type(3) is int
  • type(3.0) is float
  • type(10**10) is long # Python 2
  • type(1 + 1j) is complex
  • type('Hello') is str
  • type([1, 2]) is list
  • type([1, [2, 'Hello']]) is list
  • type({'city': 'Paris'}) is dict
  • type((1,2)) is tuple
  • type(set()) is set
  • type(frozenset()) is frozenset
  • ----
  • type(3).__name__ == "int"
  • type('Hello').__name__ == "str"
  • ----
  • import types, re, Tkinter # For the following examples
  • type(re) is types.ModuleType
  • type(re.sub) is types.FunctionType
  • type(Tkinter.Frame) is types.ClassType
  • type(Tkinter.Frame).__name__ == "classobj"
  • type(Tkinter.Frame()).__name__ == "instance"
  • type(re.compile('myregex')).__name__ == "SRE_Pattern"
  • type(type(3)) is types.TypeType

The type function disregards class inheritance: "type(3) is object" yields False while "isinstance(3, object)" yields True.

Links:

Isinstance

edit

Determines whether an object is an instance of a type or class.

The following tests return True:

  • isinstance(3, int)
  • isinstance([1, 2], list)
  • isinstance(3, object)
  • isinstance([1, 2], object)
  • import Tkinter; isinstance(Tkinter.Frame(), Tkinter.Frame)
  • import Tkinter; Tkinter.Frame().__class__.__name__ == "Frame"

Note that isinstance provides a weaker condition than a comparison using #Type.

Function isinstance and a user-defined class:

class Plant: pass # Dummy class class Tree(Plant): pass # Dummy class derived from Plant tree = Tree() # A new instance of Tree class print(isinstance(tree, Tree)) # True print(isinstance(tree, Plant)) # True print(isinstance(tree, object)) # True print(type(tree) is Tree) # True print(type(tree).__name__ == "instance") # False print(tree.__class__.__name__ == "Tree") # True 

Links:

Issubclass

edit

Determines whether a class is a subclass of another class. Pertains to classes, not their instances.

class Plant: pass # Dummy class class Tree(Plant): pass # Dummy class derived from Plant tree = Tree() # A new instance of Tree class print(issubclass(Tree, Plant)) # True print(issubclass(Tree, object)) # False in Python 2 print(issubclass(int, object)) # True print(issubclass(bool, int)) # True print(issubclass(int, int)) # True print(issubclass(tree, Plant)) # Error - tree is not a class 

Links:

Duck typing

edit

Duck typing provides an indirect means of reflection. It is a technique consisting in using an object as if it was of the requested type, while catching exceptions resulting from the object not supporting some of the features of the class or type.

Links:

Callable

edit

For an object, determines whether it can be called. A class can be made callable by providing a __call__() method.

Examples:

  • callable(2)
    • Returns False. Ditto for callable("Hello") and callable([1, 2]).
  • callable([1,2].pop)
    • Returns True, as pop without "()" returns a function object.
  • callable([1,2].pop())
    • Returns False, as [1,2].pop() returns 2 rather than a function object.

Links:

Returns the list of names of attributes of an object, which includes methods. Is somewhat heuristic and possibly incomplete, as per python.org.

Examples:

  • dir(3)
  • dir("Hello")
  • dir([1, 2])
  • import re; dir(re)
    • Lists names of functions and other objects available in the re module for regular expressions.

Links:

Getattr

edit

Returns the value of an attribute of an object, given the attribute name passed as a string.

An example:

  • getattr(3, "imag")

The list of attributes of an object can be obtained using #Dir.

Links:

Keywords

edit

A list of Python keywords can be obtained from Python:

import keyword pykeywords = keyword.kwlist print(keyword.iskeyword("if")) # True print(keyword.iskeyword("True")) # False 

Links:

Built-ins

edit

A list of Python built-in objects and functions can be obtained from Python:

print(dir(__builtins__)) # Output the list print(type(__builtins__.list)) # = <type 'type'> print(type(__builtins__.open)) # = <type 'builtin_function_or_method'> print(list is __builtins__.list) # True print(open is __builtins__.open) # True 

Links:

edit