8

I am browsing the Python source and noticed a C implementation for heapq, as well as a Python implementation. Why are there both? Which one is used when I import heapq from CPython?

1 Answer 1

7

import heapq imports the Python implementation. You can confirm that by inspecting the value of heapq in the interative interpreter:

In [20]: import heapq

In [21]: heapq
Out[21]: <module 'heapq' from '/usr/lib/python2.7/heapq.pyc'>

heapq.pyc is the byte-compiled version of the heapq.py module.

However, inside the heapq.py file is:

# If available, use C implementation
try:
    from _heapq import *
except ImportError:
    pass

_heapqmodule.c provides the _heapq module. So if the C implementation is available, import heapq uses the C implementation.

Sign up to request clarification or add additional context in comments.

5 Comments

Note that this is a common pattern across a number of performance-sensitive Python libraries.
I see. In what case would the compiled library be unavailable?
@Gareth: While CPython is the most commonly used implementation of Python, there are others, such as Jython, IronPython, and PyPy. Some implementations (in particular the Java-based Jython) may use the Python implementation as a base but not the C implementation.
Besides supporting VM-based Python implementations with no C support, mail.python.org/pipermail/python-dev/2008-October/083078.html mentions another reason you'll see dual Python/C implementations: the Python version came first, was supplanted by the C version for speed, but kept around for documentation, regression testing, and forkability.
How can you tell which is actually being used though.? would calling heapq after importing tell you something different?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.