Python Explore Python modules and objects

Python Exploring Python’s Modules and Objects. You can interactively explore modules and objects directly within the Python interpreter. This is an underrated feature that’s easily overlooked, especially for those who have just switched to Python from another language.
With many programming languages, it’s difficult to understand the internals of a package or class without consulting the online documentation or carefully studying the interface definition.
Unlike Python, productive developers spend a significant amount of time interactively using the interpreter in the Python REPL session. I often write small snippets of code in the REPL session and then copy and paste them into the Python file I’m working on in my editor.
This section describes two simple techniques for interactively exploring Python classes and methods within the interpreter.
These techniques work with any installation of Python Tutorial. Simply launch the Python interpreter from the command line using the python command. This is particularly useful for debugging sessions on systems where advanced editors or IDEs are unavailable, such as when working over a network (ssh) in a terminal session.
Ready? Let’s get started! Suppose you’re writing a program that uses the datetime module from the Python standard library. How can you determine which functions or classes this module exports, and what methods and attributes those classes contain?
One approach is to use a search engine or look up the official Python documentation online. Alternatively, you can access this information directly in the Python REPL using the built-in Python dir() function:

>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '_divide_and_round',
'date', 'datetime', 'datetime_CAPI', 'time',
'timedelta', 'timezone', 'tzinfo']

In the example above, we first import the datetime module from the standard library, then use the dir() function to inspect the module. Calling dir() on a module returns an alphabetical list of its name and attributes.
Since everything in Python is an object, this technique works not only for modules themselves, but also for classes and data structures exported by modules.
In fact, we can continue to call dir() on the objects of interest. For example, the following shows the datetime.date class:

>>> dir(datetime.date)
['__add__', '__class__', ..., 'day', 'fromordinal',
'isocalendar', 'isoformat', 'isoweekday', 'max', 'min',
'month', 'replace', 'resolution', 'strftime',
'timetuple', 'today', 'toordinal', 'weekday', 'year']

As you can see, dir() allows you to quickly browse the contents available within a module or class. If you can’t remember the exact spelling of a particular class or function, using dir() allows you to view the relevant information without interrupting your coding flow.
Calling dir() on an object like a complex module or class can sometimes produce lengthy output that’s difficult to read quickly. Here’s a trick to filter the list of attributes of interest:

>>> [_ for _ in dir(datetime) if 'date' in _.lower()]
['date', 'datetime', 'datetime_CAPI']

Here, a list comprehension is used to filter the results of the dir(datetime) call, displaying only names containing the word “date”. Note that I call the lower() method on each name to ensure case-insensitive filtering.
Simply listing an object’s attributes is sometimes not enough to solve the problem at hand. So, how can we get more detailed information about the functions and classes exported by the datetime module?
You can use Python’s built-in help() function to browse the automatically generated documentation for all Python objects in Python’s interactive help system:

>>> help(datetime)

If you run the above example in a Python interpreter session, the terminal will display a text-based help page with information about the datetime module, as shown below:

Help on module datetime:

NAME
datetime - Fast implementation of the datetime type.

CLASSES
builtins.object
date
datetime
time

Use the up and down arrow keys to scroll through the documentation. Pressing the spacebar scrolls down several lines at a time. Pressing q exits the interactive help mode and returns you to the interpreter session. Pretty neat, right?
By the way, you can call help() on all Python objects, including other built-in functions and custom Python classes. The Python interpreter automatically generates help documentation based on the object and its documentation string (if any). The following usages of help() are all correct:

>>> help(datetime.date)
>>> help(datetime.date.fromtimestamp)
>>> help(dir)

Of course, dir() and help() are no match for well-formatted HTML documentation, search engines, or Stack Overflow. However, these two functions can be used to quickly find relevant information without leaving the Python interpreter and can be used offline, which can be very useful in certain situations.

Key Points

  • Use the built-in dir() function to interactively explore modules and classes within a Python interpreter session.

  • The built-in help() function can be used to browse documentation directly within the interpreter (press q to quit).

Leave a Reply

Your email address will not be published. Required fields are marked *