Skip to content

Commit fac858f

Browse files
Introduce a proper sequence type
1 parent 65650a6 commit fac858f

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

cons/core.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,24 @@ def __init__(self):
172172
raise NotImplementedError()
173173

174174

175+
class ProperSequenceType(ABCMeta):
176+
"""An abstract type that can be used as an instance check for proper sequences.
177+
178+
A proper sequence is a sequence according to `cons` but not a `ConsPair`.
179+
"""
180+
181+
def __instancecheck__(self, o):
182+
return issubclass(type(o), MaybeCons)
183+
184+
185+
class ProperSequence(metaclass=ProperSequenceType):
186+
"""A sequence according to `cons` but not a `ConsPair`."""
187+
188+
@abstractmethod
189+
def __init__(self):
190+
raise NotImplementedError()
191+
192+
175193
class NonCons(ABC):
176194
"""A class (and its subclasses) that is *not* considered a cons.
177195

tests/test_cons.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,14 @@
77
from unification import unify, reify, var
88

99
from cons import cons, car, cdr
10-
from cons.core import ConsPair, MaybeCons, ConsNull, ConsError, NonCons
10+
from cons.core import (
11+
ConsPair,
12+
MaybeCons,
13+
ConsNull,
14+
ConsError,
15+
NonCons,
16+
ProperSequence,
17+
)
1118

1219

1320
def test_noncons_type():
@@ -68,6 +75,19 @@ def test_cons_null():
6875
assert not isinstance(cycle([5]), ConsNull)
6976

7077

78+
def test_proper_sequence_type():
79+
80+
with pytest.raises(TypeError):
81+
ProperSequence()
82+
83+
assert not isinstance(cons(1, 2), ProperSequence)
84+
assert not isinstance(cons(1, 2, 3), ProperSequence)
85+
assert not isinstance("hi", ProperSequence)
86+
assert not isinstance(1, ProperSequence)
87+
assert isinstance([], ProperSequence)
88+
assert isinstance((1, 2, 3), ProperSequence)
89+
90+
7191
def test_cons_join():
7292

7393
with pytest.raises(ValueError):

0 commit comments

Comments
 (0)