Python Programming/Reflection

From Wikibooks, open books for an open world
Jump to navigation Jump to search


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 | edit source]

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 | edit source]

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 | edit source]

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 | edit source]

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 | edit source]

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:

Dir[edit | edit source]

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 | edit source]

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 | edit source]

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 | edit source]

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:

External links[edit | edit source]