Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prevent tuple subclasses from being interpreted as generic #3768

Merged
merged 10 commits into from Oct 15, 2023

Conversation

tybug
Copy link
Member

@tybug tybug commented Oct 13, 2023

closes #3767.

Hypothesis is actually doing the "right" thing here. class Thing(namedtuple("Thing", [])) is a subclass of tuple which is both generic and a sequence. So providing concrete instantiations of Thing to eg st.from_type(Sequence[int]) type checks.

But, this seems to me like undesirable behavior: users treat namedtuples more like a struct or dataclass and not as either generic or a collection. I've special-cased an exception against namedtuples here - but let me know if you prefer a different approach. After discussion, this PR instead prevents any tuple subclasses from being interpreted as generic.

Comment on lines 410 to 425
# namedtuples are, strictly speaking, generic. However, users treat them as
# dataclasses or structs, not as a generically typed collection, so we
# don't want to provide generic instantiations of these.
#
# Namedtuples aren't an actual type, so we'll check for internal attributes
# set by collections.namedtuple and hope nobody sets these on their own
# tuple subclass.
for t in sorted(mapping, key=type_sorting_key):
if (
isinstance(t, type)
and issubclass(t, tuple)
and hasattr(t, "_fields")
and hasattr(t, "_asdict")
):
mapping.pop(t)

Copy link
Member Author

@tybug tybug Oct 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure where this should appear in the function order-wise. There's a portion lower down where mapping is iterated over in the same way - maybe this check belongs there?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On line 395 above it drops things which are exactly type tuple, maybe we could expand that to drop any subtype of tuple too?

Copy link
Member

@Zac-HD Zac-HD Oct 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems reasonable, yeah. I think we'd want to discard os.Environ first, and then if there are non-tuple types discard all the tuple types. It's important that if you're resolving a namedtuple, or union of several, that works without discarding all or all-but-one!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated as you described: if there is at least one other type, drop all tuple (sub)classes.

I admit I'm not sure what input to st.from_type would cause mapping to be filled with only tuple subclasses. This might be relevant if the cover tests yell at me for not providing an input which fails the new conditional branch 🙂

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need something along the lines of:

import abc

class AbstractStruct(abc.ABC, tuple):
    @abstractmethod
    def foo(self): ...

class ConcreteA(AbstractStruct):
    def foo(self): pass
class ConcreteB(AbstractStruct):
    def foo(self): pass

def test_handles odd tuple_subclasses():
    s = st.from_type(AbstractStruct)
    assert_all_examples(s, lambda x: isinstance(x, AbstractStruct))
    find_any(s, lambda x: isinstance(x, ConcreteA))
    find_any(s, lambda x: isinstance(x, ConcreteB))

Copy link
Member Author

@tybug tybug Oct 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, I don't think this works, because AbstractStruct doesn't pass this conditional:

if isinstance(thing, types.typing_root_type) or (
sys.version_info[:2] >= (3, 9)
and isinstance(get_origin(thing), type)
and get_args(thing)
):
return types.from_typing_type(thing)

I managed to come up with an alternative test involving a custom protocol whose only concrete instantiations are tuple subtypes - let me know what you think.

@tybug tybug changed the title prevent namedtuple from being interpreted as sequences prevent tuple subclasses from being interpreted as generic Oct 14, 2023
hypothesis-python/RELEASE.rst Outdated Show resolved Hide resolved
Comment on lines 410 to 425
# namedtuples are, strictly speaking, generic. However, users treat them as
# dataclasses or structs, not as a generically typed collection, so we
# don't want to provide generic instantiations of these.
#
# Namedtuples aren't an actual type, so we'll check for internal attributes
# set by collections.namedtuple and hope nobody sets these on their own
# tuple subclass.
for t in sorted(mapping, key=type_sorting_key):
if (
isinstance(t, type)
and issubclass(t, tuple)
and hasattr(t, "_fields")
and hasattr(t, "_asdict")
):
mapping.pop(t)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need something along the lines of:

import abc

class AbstractStruct(abc.ABC, tuple):
    @abstractmethod
    def foo(self): ...

class ConcreteA(AbstractStruct):
    def foo(self): pass
class ConcreteB(AbstractStruct):
    def foo(self): pass

def test_handles odd tuple_subclasses():
    s = st.from_type(AbstractStruct)
    assert_all_examples(s, lambda x: isinstance(x, AbstractStruct))
    find_any(s, lambda x: isinstance(x, ConcreteA))
    find_any(s, lambda x: isinstance(x, ConcreteB))

Copy link
Member

@Zac-HD Zac-HD left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation looks great, thanks Liam!

See comment about an additional test case, and the release note formatting, then I think we're ready to merge 😁

pass


def test_only_tuple_subclasses_in_typing_type():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd just skip this on Python 3.8, since it's using later typing features.

If we could also get a subclassing-based test working that'd make me more confident that future changes won't accidentally break something, but I'd be happy to merge without that too.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I slept on it, but I'm drawing a blank on a subclassing-based test (as opposed to using Protocol) where the only valid types are tuple types. I'd be happy to add it if someone else can come up with one, though.

Copy link
Member

@Zac-HD Zac-HD left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rereading the full history here, yeah, you're right about the abstract class not actually working 😅

So I think it's ready to merge!

@Zac-HD Zac-HD enabled auto-merge October 15, 2023 22:26
@Zac-HD Zac-HD merged commit a331d3e into HypothesisWorks:master Oct 15, 2023
47 checks passed
@tybug tybug deleted the namedtuple-generic branch October 15, 2023 23:32
@tybug
Copy link
Member Author

tybug commented Oct 15, 2023

Thanks Zac! Happy to land my first contribution in Hypothesis, and looking forward to contributing more in the future!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incompatible Sequence types generated after register_type_strategy()
3 participants