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

Better handling of covariance, contravariance, and TypeVar in from_type() #2094

Closed
Zac-HD opened this issue Sep 17, 2019 · 0 comments · Fixed by #2169
Closed

Better handling of covariance, contravariance, and TypeVar in from_type() #2094

Zac-HD opened this issue Sep 17, 2019 · 0 comments · Fixed by #2169
Labels
enhancement it's not broken, but we want it to be better

Comments

@Zac-HD
Copy link
Member

Zac-HD commented Sep 17, 2019

if isinstance(thing, typing.TypeVar):
if getattr(thing, "__bound__", None) is not None:
return st.from_type(thing.__bound__)
if getattr(thing, "__constraints__", None):
return st.shared(
st.sampled_from(thing.__constraints__), key="typevar-with-constraint"
).flatmap(st.from_type)
# Constraints may be None or () on various Python versions.
return st.text() # An arbitrary type for the typevar

Type variables are tricky!

  • We should handle constraints before bounds. They're mutually exclusive, but easier to handle the "neither" case that way.
  • The shared() strategy should be keyed on f"typevar-{thing.__name__}"
  • The bounds case should also use shared()! Otherwise it's not really a typevar...
  • We can use a (shared() of) from_type(getattr(thing, "__bound__", object)) to generalise the text() hack.

A larger problem is that from_type() currently always treats things as covariant (i.e. returns a strategy for subtypes if the exact type is unknown). We should probably provide an argument for in/co/contra variance and default to invariance, which will be an annoying deprecation pathway. Plus use that from the TypeVar handling, obviously.

(this should be retagged from enhancement to bug if it's seen in the wild)

@Zac-HD Zac-HD added the enhancement it's not broken, but we want it to be better label Sep 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement it's not broken, but we want it to be better
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant