Can global variable be passed into Python function?

Chris Angelico rosuav at gmail.com
Sun Mar 2 05:07:39 EST 2014


On Sun, Mar 2, 2014 at 8:35 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> 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
>
> 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?

In the absence of any advice to the contrary, I would use == to test.
The flags are most likely to be, in order:

* An enumeration, in a sufficiently new Python
* Integers
* Strings
* Arbitrary object()s

All of the above will compare correctly with ==, and if someone stuffs
in an object that compares equal to more than one of them, they're
likely to have problems at the far end. If identity is really crucial,
I would expect there to be a comment in the docs.

And there's another thing you can do to test.

>>> import os
>>> type(os.POSIX_FADV_RANDOM)
<class 'int'>

So use ==. If it's later changed and you have to instead use 'is', you
can change your code.

ChrisA



More information about the Python-list mailing list