Conditional refactorings

I have been reading through some of the source code from the requests library. This is one of the more well-known, well-used, well-loved, and well-praised Python libraries I know of. I came across some conditional code which I personally would refactor. A first refactor I’m pretty confident about whilst a second I’m less certain is an improvement. I’ll detail them both and welcome any comments anyone has. A specific example of this kind of conditional comes in the adapters module specifically the cert_verify method. Here is the code in question, slightly snipped for brevity: ...

April 21, 2017

Minor Refactorings

Looking through the code of an open-source Python project I came across code that amounts to the following: host_name = self.connection.getsockname()[0] if self.server.host_name is not None: host_name = self.server.host_name This looks odd because if the condition is True then we forget about the host_name derived from the call to self.connection.getsockname. However it could be that that call has some side-effect. Assuming that it does not we can re-write the above code as: if self.server.host_name is not None: host_name = self.server.host_name else: host_name = self.connection.getsockname()[0] Or even, if you prefer: ...

February 7, 2017