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

Conditional class import #1107

Closed
JukkaL opened this issue Jan 8, 2016 · 5 comments
Closed

Conditional class import #1107

JukkaL opened this issue Jan 8, 2016 · 5 comments
Labels

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Jan 8, 2016

It's pretty common to conditionally import a class. Here is a synthetic example:

try:
    from m1 import C
except ImportError:
    from m2 import CC as C

It's not quite obvious how code like the above should be type checked, as m1.C and m2.CC generally don't have identical interfaces.

See also #649.

@refi64
Copy link
Contributor

refi64 commented Jan 8, 2016

Maybe Mypy could set C's type to the intersection (all the common attributes/methods) of m1.C and m2.CC.

@JukkaL
Copy link
Collaborator Author

JukkaL commented Jan 9, 2016

That just might work. There are still some details that are non-obvious -- for example, what happens if the type of an attribute or a method argument is different is m1.C and m2.C. Also, generating useful error messages when accessing an attribute defined in m1.C but not m2.CC, for example, would need some extra logic.

Implementation-wise, we could internally create a new class that is a subclass of only the common base classes of m1.C and m2.CC, and only includes definitions that are implemented by both of the classes. The class would not be a subclass of either m1.C or m2.CC, which might be a problem.

@lkraider
Copy link

lkraider commented Mar 2, 2017

Wouldn't it effectively be treated as an Union[C, CC] for the code that performs this conditional import?

@gvanrossum gvanrossum removed this from the 0.5 milestone Mar 29, 2017
@NYKevin
Copy link

NYKevin commented Nov 25, 2017

Wouldn't it effectively be treated as an Union[C, CC] for the code that performs this conditional import?

No, that fails to ensure that every instance is of the same type (thus causing problems for binary operator overrides, among other things). However, I would think that TypeVar('C', m1.C, m2.CC) would be entirely suitable for this use case.

@JukkaL JukkaL added the false-positive mypy gave an error on correct code label May 18, 2018
@JukkaL
Copy link
Collaborator Author

JukkaL commented Jan 28, 2020

This seem too difficult to fix relative to the benefit. Generally using # type: ignore is an acceptable workaround.

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

No branches or pull requests

6 participants