public inbox for cygwin@cygwin.com
 help / color / mirror / Atom feed
* Weird results from PyIter_Check
@ 2022-04-02 19:07 airplanemath
  0 siblings, 0 replies; only message in thread
From: airplanemath @ 2022-04-02 19:07 UTC (permalink / raw)
  To: cygwin

[-- Attachment #1: Type: text/plain, Size: 1635 bytes --]

PyIter_Check appears to be the C-level equivalent of
isinstance(..., collections.abc.Iterator), testing whether the python
next() or the C PyIter_Next will succeed.  However, PyIter_Check
disagrees with collections.abc.Iterator and next about whether a given
object is an iterator.  

$ cat test_iterator.pyx
from cpython.iterator cimport PyIter_Check

def is_iterator(obj: object) -> bool:
    """Check whether obj is an iterator.

    Should agree with isinstance(obj, collections.abc.Iterator).

    Parameters
    ----------
    obj : object

    Returns
    -------
    bool
    """
    return PyIter_Check(obj)

$ cythonize --build --inplace test_iterator.pyx
running build_ext

$ python
Python 3.9.10 (main, Jan 20 2022, 21:37:52)
[GCC 11.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test_iterator, os, fractions, collections.abc
>>> test_iterator.is_iterator(os.environ)
True
>>> isinstance(os.environ, collections.abc.Iterator)
False
>>> next(os.environ)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '_Environ' object is not an iterator
>>> test_iterator.is_iterator(fractions.Fraction(0, 1))
True
>>> isinstance(fractions.Fraction(0, 1), collections.abc.Iterator)
False
>>> next(fractions.Fraction(0, 1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Fraction' object is not an iterator

On Linux, the test function using PyIter_Check agrees with
collections.abc.Iterator and next.  The test case that led me to this
behaviour works the same in Windows as on Linux.  Is this expected behavior?


[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: Type: text/x-python3, Size: 1 bytes --]



^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2022-04-02 19:07 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-04-02 19:07 Weird results from PyIter_Check airplanemath

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).