Back
Close

Journey to Master Python (WIP)

ageekymonk
18.9K views

Introspection

Ability to look at the type of the object at runtime is one of powerful features of python. You can look at the type, function signature, code and even disassembled bytecode at runtime.

Handling type at runtime

We can at runtime find the type of the object and handle actions accordingly.

What if you want to find the type of the inherited object. using type(something) will not accomplish to check for parent class but isinstance(something, parentclass) will achieve it

Using isinstance function we can create other checks for function, module, class etc can be implemented. Though they are already implemented in inspect module

The above code is exactly how isfunction function in inspect module is implemented.

Inspecting the Function Signature

You can inspect the function signature using the inspect module. you can use __annotations__ attribute to get the annotations of a function.

Example: Using Introspection for Validating Parameters

Below is an example where we use inspection to write a Decorator to validate if the passed parameters are of correct type.

Function Introspection
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants