Difference between 'is' and '=='
Ross Ridge
rridge at csclub.uwaterloo.ca
Tue Mar 28 18:18:10 EST 2006
Felipe Almeida Lessa wrote:
> That said, you can do thinks like:
> >>> import socket
> >>> a = socket.AF_UNIX
> >>> a is socket.AF_UNIX
> True
>
> That kind of constants can be used with "is". But if don't want to be
> prone to errors as I do, use "is" only when you really know for sure
> that you're dealing with singletons.
It's only safe to to compare address family values with socket.AF_UNIX
using "is", if small integers are guaranteed to be singletons, and
socket.AF_UNIX has one of those small values. Otherwise, address
family values equal in value to socket.AF_UNIX can be generated using
different objects. There's no requirement that the socket module or
anything else return values using the same object that the
socket.AF_UNIX constant uses.
Consider this example using the socket.IPPROTO_RAW constant:
>>> socket.getaddrinfo("localhost", None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)[0][2] is socket.IPPROTO_RAW
False
>>> socket.getaddrinfo("localhost", None, socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)[0][2] == socket.IPPROTO_RAW
True
Ross Ridge
More information about the Python-list
mailing list