It seems currently it is rather hard to override mimetypes.guess_extension
result despite mimetypes.init
docs says
Each file named in files or knownfiles takes precedence over those named before it.
I suggest to allow overrides for mapping of MIME types to file name extension. I am realizing that this change may be a breaking one for some users and I would be happy if somebody will propose a better solution.
My idea is that MimeTypes.add_type
call should give priority to the passed extension, so that next guess_extension
returns it. In addition, fallback=False
argument may be added to add_type
and read
methods to add association only if there is no current mapping.
I have a patch, but it is recommended to create an issue for each pull request and feature request should be discussed at first.
Consider the following case. At first glance the issue may be considered as a rather specific one and applicable only to combination particular Python version and Linux distribution. It can not be reproduced with Python-3.12 (#97646), but since IANA media types registry receives updates, I anticipate similar troubles in future.
Debian 12 bookworm was released with Python-3.11 having
'.js': 'application/javascript'
mapping. On the other hand the media-types package contains
/etc/mime.types:text/javascript es js mjs
due to changes recommended in RFC9239: Updates to ECMAScript Media Types (https://datatracker.ietf.org/doc/rfc9239/
)
The result of different pace of registry changes adoption is
python3 -m mimetypes --extension text/javascript
.es
It can not be changed to “.js” by calling mimetypes.init
with a custom mapping file. Or by an additional call of add_type
. From my point of view, it is contradiction with the documented behavior.
The ultimate goal is to make guess_type
and guess_extension
mapping reciprocal and to avoid at least for canonical mappings
python3 -m mimetypes 'test.js'
type: text/javascript encoding: None
python3 -m mimetypes --extension text/javascript
.es