Showing posts with label introspection. Show all posts
Showing posts with label introspection. Show all posts


Some Python introspection

Python has very powerful introspection capabilities. These let you examine any object (and everything is an object in Python) and extract information about it.

I am currently writing a script to monitor licenses for Matlab, and found occasion to use introspection. I have a string which is the name of a local variable in a function, and I want to extract the value of that local variable. (The variable is really an argument passed to the function.) Having the name of the variable as a string, how do I get its value?  Use the locals() function. locals() returns a dictionary of local variables.

    def check_licenses(checked_out=0, warning=10, critical=15): 
        # checked_out, warning, and critical are now local variables
        levels = ('warning', 'critical')
        for l in levels:
            if checked_out >= locals()[l]:
                print 'Licenses checked out are above threshold %s' % (l)

I found this mailing list post very useful.