I was looking through the source code for the imghdr
module, which is part of the python standard library (I use 2.7). The structure is pretty simple—a what
function that iterates over a list of functions with names like test_filetype
, and if the passed in file matches any of the tests, it returns the string for that filetype.
All of the test_filetype
functions take two arguments, h
and f
. h
is a string with the contents of f.read(32)
, and f
is the open file object. None of the test_filetype
functions actually use f
for anything.
Why would the set of test_filetype
functions all take an argument that is never used?
My guess is that this is to allow for custom functions to be added to
imghdr.tests
. From the documentation ofimghdr
module -As can be seen from documentation, the
imghdr
module allows extension to thetests
list. I think the addition argumentf
could be there for these custom functions that are added to this list.Taking a look at the
imghdr.what()
function -As can be seen, when we send in a filename to
what()
function, it only reads the first 32 bytes from the file and only sends those 32 bytes in theh
argument of thetest
function , I believe the additionalf
argument maybe for cases where the first32
bytes are not enough to determine the image format (especially for custom tests).