Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python heapq - Python and C implementation? Which one is used?

Tags:

python

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?

like image 416
Gareth Avatar asked Mar 24 '15 22:03

Gareth


1 Answers

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.

like image 67
unutbu Avatar answered Sep 30 '22 17:09

unutbu