Python introspection

Functions, variables and objects can be usedintrospection.

First, usehelp()Global functions, if provided in the form of docstring, we can get documentation.

Then, you can use print() to get information about the function:

def increment(n):
    return n + 1

print(increment)

# <function increment at 0x7f420e2973a0>

Or object:

class Dog():
    def bark(self):
        print('WOF!')

roger = Dog()

print(roger)

# <main.Dog object at 0x7f42099d3340>

Thistype()The function provides us with the type of object:

print(type(increment))
# <class 'function'>

print(type(roger)) # <class ‘main.Dog’>

print(type(1)) # <class ‘int’>

print(type(‘test’)) # <class ‘str’>

Thisdir()Global functions enable us to find all methods and properties of an object:

print(dir(roger))

# [‘class’, ‘delattr’, ‘dict’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘module’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘setattr’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘weakref’, ‘bark’]

Thisid()The global function shows us the location of any object in memory:

print(id(roger)) # 140227518093024
print(id(1))     # 140227521172384

It may be useful to check whether two variables point to the same object.

ThisinspectThe standard library module provides us with more tools to obtain information about the object, you can view it here:https://docs.python.org/3/library/inspect.html


More python tutorials: