Is email.message.get() case insensitive for the header name?

Peter Otten __peter__ at web.de
Mon Feb 15 04:38:57 EST 2021


On 14/02/2021 21:50, Chris Green wrote:

> It isn't clear from the documentation. Does email.message.get() care
> about the case of the header it's getting?
> 
> I checking mailing list mails and the "List-Id:" header is a bit
> 'mixed', i.e. it can be List-Id:, or List-ID: or list-id:, will
> email.message.get("List-Id:", "unknown") find all of them?
Let's have a look:

 >>> import email.message
 >>> email.message.get
Traceback (most recent call last):
   File "<pyshell#19>", line 1, in <module>
     email.message.get
AttributeError: module 'email.message' has no attribute 'get'


OK, you probably meant

 >>> email.message.Message.get
<function Message.get at 0x031AEBB0>


Enter the inspect module for a quick glance at the method's source:

 >>> import inspect
 >>> print(inspect.getsource(email.message.Message.get))
     def get(self, name, failobj=None):
         """Get a header value.

         Like __getitem__() but return failobj instead of None when the 
field
         is missing.
         """
         name = name.lower()
         for k, v in self._headers:
             if k.lower() == name:
                 return self.policy.header_fetch_parse(k, v)
         return failobj

Both the `name` argument and the header keys are converted to lowercase 
before the comparison, so yes, the method is case-insensitive (whether 
it should be casefold() doesn't matter for ascii-strings).



More information about the Python-list mailing list