Skip to content

Conditional class import #1107

Closed
Closed

Description

@JukkaL

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.

Activity

  1. refi64 commented on Jan 8, 2016

    @refi64
    Contributor

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

  2. JukkaL commented on Jan 9, 2016

    @JukkaL
    CollaboratorAuthor

    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.

  3. added this to the milestone on Mar 2, 2016
  4. lkraider commented on Mar 2, 2017

    @lkraider

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

  5. removed this from the milestone on Mar 29, 2017
  6. NYKevin commented on Nov 25, 2017

    @NYKevin

    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.

  7. JukkaL commented on Jan 28, 2020

    @JukkaL
    CollaboratorAuthor

    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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions