Can global variable be passed into Python function?

Marko Rauhamaa marko at pacujo.net
Sun Mar 2 04:35:43 EST 2014


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:

> On Sat, 01 Mar 2014 19:29:41 +0200, Marko Rauhamaa wrote:
>> Michael Torrie <torriem at gmail.com>:
>>> No, '==' works fine no matter what objects you assign to your state
>>> variables.
>> 
>> Well, it doesn't since
>> 
>>    >>> a = float("nan")
>>    >>> a is a
>>    True
>>    >>> a == a
>>    False
>
> No, that is working correctly, so the comment that equals works fine
> is correct: returning False is the correct thing to do if one or both
> of the objects are a NAN. NANs are supposed to compare unequal to
> everything, including themselves.

Nobody is saying there's a bug in the implementation of "==". I'm just
saying "==" cannot be taken as a universal superset of "is". Therefore
a program cannot blindly use "==" to test for identity.

That's why "==" is a bit fishy. It immediately raises the question: what
does it mean for a == b, especially since the exact implementation of a
and b are intended to be opaque.

Example:

The os module defines the constants os.SEEK_SET, os.SEEK_CUR and
os.SEEK_END that can be used as arguments for os.lseek(). Must those
constants be used, or can a regular integer be used instead? The
documentation clearly states that integers can be used:

   SEEK_SET or 0 to set the position relative to the beginning of the
   file; SEEK_CUR or 1 to set it relative to the current position;
   SEEK_END or 2 to set it relative to the end of the file.

However, on the same reference page, os.posix_fadvise() is defined. We
read:

   advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
   POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED or
   POSIX_FADV_DONTNEED

and:

    os.POSIX_FADV_NORMAL
    os.POSIX_FADV_SEQUENTIAL
    os.POSIX_FADV_RANDOM
    os.POSIX_FADV_NOREUSE
    os.POSIX_FADV_WILLNEED
    os.POSIX_FADV_DONTNEED

    Flags that can be used in advice in posix_fadvise()

Now, what kinds of object are those constants? We are not supposed to
know or care. We could peek into the implementation, but it would be a
grave mistake to trust the implementation choices in the application.

So in my application code I might set:

   favd_flag = os.POSIX_FADV_RANDOM

in some other part of my code I might want to see how "flag" was set.
Should I use "==" or "is" to test it?

If I take the API documentation on its face value, I *must* use "==" for
os.SEEK*:

    if seek_flag == os.SEEK_END:
        ...

and I *must* use "is" for os.POSIX_FAVD_*:

    if fsavd_flag is os.POSIX_FADV_RANDOM:
        ...

Since, for all I know, os.POSIX_FAVD_RANDOM might return a random value
for __eq__().


Marko



More information about the Python-list mailing list