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

wishlist: type inference in branches #2762

Open
jdemeyer opened this Issue Dec 17, 2018 · 5 comments

Comments

Projects
None yet
4 participants
@jdemeyer
Copy link
Contributor

jdemeyer commented Dec 17, 2018

Very often, I find myself writing code of the form

if isinstance(x, SomeType):
    y = <SomeType>x
    # do something with y

It would be really cool if Cython would automatically know that x is of type SomeType inside that branch.

@scoder

This comment has been minimized.

Copy link
Contributor

scoder commented Dec 28, 2018

That would be nice, yes. It might be relatively easy to achieve in the current assignment based type inference, by injecting a fake typed assignment at the start of the if-block (preferably one that repeats the previously assigned value, if any). We are still waiting for the "better type inference" to come, but until then, I think we should try to bend what we have as far as we can.

@rth

This comment has been minimized.

Copy link

rth commented Dec 28, 2018

It would be really cool if Cython would automatically know that x is of type SomeType inside that branch.

That's not guaranteed though,

>>> import numbers
>>> x = 1
>>> isinstance(x, numbers.Number)
True
>>> type(x)
int

it could be a subclass.

@scoder

This comment has been minimized.

Copy link
Contributor

scoder commented Dec 28, 2018

I think it would be reasonable to restrict this to extension types and builtins for now, anything that Cython can actually make use of. But yes, builtins have the problem of requiring exact types, not arbitrary subtypes. So a fake assignment might not work for them. This would still work for extension types, though.

@robertwb

This comment has been minimized.

Copy link
Contributor

robertwb commented Dec 28, 2018

@scoder

This comment has been minimized.

Copy link
Contributor

scoder commented Dec 28, 2018

Right. The inferred type of the variable would still be object (usually), since it's assigned globally to the function scope.

However, we do keep the set of latest assignments for each NameNode after the control flow analysis. Inside of the if-block, there would only be one assignment (or some other dedicated way to express the type check), and the type analysis (and later phases) could therefore know the specific type of the current value, even if the type of the variable is more general.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment