rubasov
rubasov

Reputation: 322

Determining if a given Python module is part of the standard library

How can I determine whether a Python module is part of the standard library? In other words: is there a Python equivalent of perl's corelist utility?

I would use this to set my expectations on portability during development. In case it's implementation dependent, I'm interested in CPython.

The best answer I found so far is this:

Which parts of the python standard library are guaranteed to be available?

That is to search for the module name on the index page of the Python Standard Library Documentation: http://docs.python.org/2/library/. However, this is less convenient than having a utility and also does not tell me anything about minimally required versions.

Upvotes: 7

Views: 667

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124258

When using a setuptools install script (setup.py), you test for the required module, and update the installation dependencies list to add backports if needed.

For example, say you need the collections.OrderedDict class. The documentation states it was added in Python 2.7, but a backport is available that works on Python 2.4 and up. In setup.py you test for the presence of the class in collections. If the import fails, add the backport to your requirements list:

from setuptools import setup

install_requires = []

try:
    from collections import OrderedDict
except ImportError:
    install_requires.append('ordereddict')

setup(
    # ...
    install_requires=install_requires
)

then in your code where you need OrderedDict use the same test:

try:
    from collections import OrderedDict
except ImportError:
    # use backported version
    from ordereddict import OrderedDict

and rely on pip or easy_install or zc.buildout or other installation tools to fetch the extra library for you.

Many recent core library additions have backports available, including json (called simplejson), argparse, sqlite3 (the pysqlite package, use from pysqlite2 import dbapi as sqlite3 as a fallback).

You'll still have to read the documentation; the Python documentation is excellent, and for new modules, classes, methods, functions or arguments the documentation mentions explicitly in what Python version they were added.

Upvotes: 9

Ned Batchelder
Ned Batchelder

Reputation: 375912

You should read the documentation for the module. You say you want a utility because reading the docs is inconvenient. But you're coding against the module? You should take a moment to read the docs in this case anyway, unless you are simply making a Frankenstein's monster by pasting together mysterious snippets you find online.

You won't be using dozens and dozens of modules, you can afford to spend a moment reading the docs. Also, generally, the docs do mention what version of Python introduced them.

The docs are good: use them.

Upvotes: 0

Related Questions