Skip to content

How to test type compatibility in Python 3.7? #570

Closed

Description

@Kimi-Arthur

With the new fixes done in Python 3.7. We cannot test type compatibility like:

type_info = List[int]
issubclass(type_info, list)

# Or

issubclass(type_info, List)

This is expected as mentioned in PEP560. So I'm not saying I should continue to write code like that.

But since it's still useful to inspect whether type is a list or not (e.g. when you inspect the object's type hints and generate a default value for it), I wonder whether these is already a known way to test such compatibility.

Thanks!

Activity

  1. changed the title [-]How to test type compatibility in Python 3?[/-] [+]How to test type compatibility in Python 3.7?[/+] on Jul 7, 2018
  2. ilevkivskyi commented on Jul 9, 2018

    @ilevkivskyi
    Member

    One possible solution is to use typing_inspect library on PyPI, it has a get_origin() function which you can use as issubclass(get_origin(type_info), list).

    But I think maybe it is time consider adding some basic introspection to typing? From all recent similar requests and general experience with typing_inspect it looks like people are interested mostly in two things:

    • Get an "erased" version of a type, i.e. a runtime class equivalent of a given type
    • Get type arguments from a given type

    @gvanrossum Does it make sense to add such two helper functions that would be essentially public wrappers around internal APIs like .__origin__ and .__args__?

  3. gvanrossum commented on Jul 9, 2018

    @gvanrossum
    Member

    Yes. I like that we make these things functions in typing rather than special attributes or methods -- it's much easier for a function to do the right thing when the type given to it is some built-in or user-defined type rather than one of the special one from typing. It should also deal with forward reference strings.

  4. Kimi-Arthur commented on Jul 9, 2018

    @Kimi-Arthur
    Author

    .__origin__ is already very helpful. Thanks! Didn't know that.

    Besides the two features you suggest, I guess testing type (either actual type or typing's type variable, like _GenericAlias) compatibility would also be useful. If this would be automatically supported by those two features, it would still be worth mentioning in that particular release's notes. Thanks!

  5. ilevkivskyi commented on Jun 20, 2019

    @ilevkivskyi
    Member

    get_origin() (an official public API for .__origin__) got into typing in Python 3.8, so I think this can be closed now.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions