Reputation: 431
I'm struggling to understand what the init() function does in the python mimetypes package. Is it an outdated function that isn't needed in more recent versions of python?
Upvotes: 4
Views: 1244
Reputation: 457
init()
will be called implicitly if you use guess_type()
, guess_all_extensions()
, guess_extension()
functions as you can see in the module source code.
But if you intend to use mimetypes.types_map
dict directly and need non-standard mimetypes i.e. 'image/webp' from mimetypes.common_types
, you need to call init()
by yourself.
$ python -c "import mimetypes; print(mimetypes.types_map['.webp'])"
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: '.webp'
$ python -c "import mimetypes; mimetypes.init(); print(mimetypes.types_map['.webp'])"
image/webp
For some functions mimetypes.init()
invoked implicitly:
$ python -c "import mimetypes; mimetypes.guess_type(''); print(mimetypes.types_map['.webp'])"
image/webp
Upvotes: 0
Reputation: 12022
mimetypes.init()
is useful if you want to add MIME type / extension mappings beyond the default. If you don't need to do that, then there's no need to call mimetypes.init()
; just use the utility functions normally, and they'll call it themselves if necessary. If you do need to do that, aside from mimetypes.init()
there's also mimetypes.read_mime_types()
and mimetypes.add_type()
.
This applies to Python 2 and 3.
Upvotes: 2
Reputation: 369344
According to the mimetypes
module documentation:
The functions described below provide the primary interface for this module. If the module has not been initialized, they will call init() if they rely on the information init() sets up.
mimetypes.init(files=None)
Initialize the internal data structures. If given, files must be a sequence of file names which should be used to augment the default type map. If omitted, the file names to use are taken from knownfiles; on Windows, the current registry settings are loaded. Each file named in files or knownfiles takes precedence over those named before it. Calling init() repeatedly is allowed.
Specifying an empty list for files will prevent the system defaults from being applied: only the well-known values will be present from a built-in list.
It's there both in Python 2.7 and Python 3.x.
Upvotes: 0