External modules

fastcore includes functionality from some modules from other projects that have been copied here, in cases where the original is no longer maintained, or where the original includes dependencies that we’d rather avoid.

imghdr

fastcore includes a copy of the Python standard library’s imghdr module, which was deprecated in Python 3.11, and removed in 3.13. However since it’s still widely used (including within fastcore), we are providing it here. We have also added some fixes to the automatic detection.

from fastcore.imghdr import what,tests
what('images/puppy.jpg')
'jpeg'

These are the tests provided:

print(', '.join(t.__name__ for t in tests))
test_jpeg, test_png, test_gif, test_tiff, test_rgb, test_pbm, test_pgm, test_ppm, test_rast, test_xbm, test_bmp, test_webp, test_exr

ansi

nbconvert provides handy functionality to convert ansi terminal codes to HTML, which we’ve copied to fastcore so they can be used without nbconvert’s prequisites. Also nbconvert doesn’t document them, so we’re showing some examples here.

from fastcore.ansi import ansi2html,strip_ansi
ansi_test = """\x1b[0;31m---------------------------------------------------------------------------\x1b[0m
\x1b[0;31mZeroDivisionError\x1b[0m                         Traceback (most recent call last)
File \x1b[0;32m<input-1>:1\x1b[0m
\x1b[0;32m----> 1\x1b[0m \x1b[38;5;241m1\x1b[39m\x1b[38;5;241m/\x1b[39m\x1b[38;5;241m0\x1b[39m

\x1b[0;31mZeroDivisionError\x1b[0m: division by zero"""
out = ansi2html(ansi_test)
print(out)
<span class="ansi-red-fg">---------------------------------------------------------------------------</span>
<span class="ansi-red-fg">ZeroDivisionError</span>                         Traceback (most recent call last)
File <span class="ansi-green-fg">&lt;input-1&gt;:1</span>
<span class="ansi-green-fg">----&gt; 1</span> <span style="color: rgb(98,98,98)">1</span><span style="color: rgb(98,98,98)">/</span><span style="color: rgb(98,98,98)">0</span>

<span class="ansi-red-fg">ZeroDivisionError</span>: division by zero
test_err = ''.join([f"<div>{o}</div>" for o in out.splitlines()])
HTML(f'<pre>{test_err}<pre>')
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
File <input-1>:1
----> 1 1/0
ZeroDivisionError: division by zero
print(strip_ansi(ansi_test))
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
File <ipython-input-1-9e1622b385b6>:1
----> 1 1/0

ZeroDivisionError: division by zero