Python Inspection Tools

One of the great things about Python is that it gives you a lot of tools out of the box that you can use to confidently explore new modules, even without an internet connection.

I’m gonna be covering (slightly) two of those tools that I often use when I am using a new module or if I’m switching from one version of Python to another.
Here are those two:

  • dir
  • help

The way I normally use them is I open up a new console window and go inside a Python interactive session, like this:

Now, I’m gonna import the “os” module and apply those 2 helper (or inspector) functions to illustrate how incredibly useful they are to programmers.

import os

Okay, once that’s done, we’re first going to use the “dir” function, and what it will do is list all the properties, functions and methods of the “os” module. It’s super simple to use, you just pass the module to it like this:

dir(os)

On the interactive window, it will return something like this:

As you can see, we get a list of all the things we can do with the “os” module. This is an extremely useful feature when you’re debugging in an environment that has no internet connection (for example, on a controlled production environment that is only connected to the local area network).

Next, we use the “help” function on one of the items in the dir result. The “help” returns the docstring of the function which would give us an idea how it works. Let’s test this on “getcwd” (but you can choose something else). To do that, just call “help” and pass the value “os.getcwd” to it:

help(os.getcwd)

This will return the help string for that module.function:

But wait! There’s more! 🙂

You can actually create this useful feature in your Python codes too, isn’t that awesome???!!! 🙂

Here’s a short demo, from within the Python interactive session.
Very simply, I just wrote a very small function called “add” with 2 parameters “n1” and “n2” and then I added a docstring (starts and ends with a triple double quotes):

def add(n1, n2):
    """ returns the sum of two numbers 'n1' and 'n2' """
    return n1 + n2

Now, let’s try “help” on our newly created function and see what happens:

Wow! Isn’t it amazing??!!

Knowing this, you can now create better systems simply by adding a docstring to your functions so that anyone who would use your functions years after you wrote them would still know why you wrote it and what it’s for.

Leave a Comment