Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is introspection useful?

I have been programming mainly in PHP, and I am trying to make a switch to python. I am skilled with PHP, and I have never needed to use introspection / introspection like capabilities. What good is code introspection, and in what situations would I find it indispensable?

Here is the only way I find it useful: From the examples I saw in 'Dive into Python', introspection basically means that you can list all of the functions and attributes of an object. To me it seems that introspection is just there as a "user's manual" to an object. It lets you look at the object and its functionality from the python shell.

I just do not see why or in what situation you would take an arbitrary object, introspect upon it, and do something useful.

like image 659
Chris D. Avatar asked Feb 21 '11 00:02

Chris D.


1 Answers

Suppose you are given a custom object and you want to know if the object has certain attributes or has as a certain method, then the introspection function such as hasattr can be used to find that out.

Also like the DiveintoPython book already illustrates, suppose you are building a GUI Editor with Auto-Completion feature, you want to get the public methods of the object which are callable at the run-time, then you can use the introspection methods like getattr for each for the methods got via dir and check if it is callable and then display it in your auto-completion list.

like image 59
Senthil Kumaran Avatar answered Oct 01 '22 16:10

Senthil Kumaran