简体   繁体   中英

How to define a type hint to a argument (the argument's value is a class, all expected value is a subclass of a certain class)?

I want to define a function. It has one argument whose value is a class. But not all classes are expected, only some subclass of a certain class can be passed.

I don't know if it is possible to use type hint to achieve this expectation.

If it does, how can I do that?

As far as I know, the type hint can only help when requiring value is a instance of certain type. And the relevant documentation is really poor.

class MyClass(object):
    pass

def my_function(arg):
    # arg should be the subclass of MyClass.
    return

I just want the definition of my_function produce the same effect of what type hint do (the only difference is that normal type hint show value is a instance of certain class, here I want it show value is a subclass of certain class).

If you are trying to say that arg must be an instance of either MyClass or some subtype of MyClass , just do this:

class MyClass(object): pass
class Child(MyClass): pass

def my_function(arg: MyClass) -> None:
    pass

my_function(MyClass())  # Type checks
my_function(Child())    # Type checks
my_function(3.14)       # Does not type check

If you are trying to say that arg must be literally the MyClass class object or a subtype, use typing.Type :

from typing import Type

# ...snip...

def my_function_2(arg: Type[MyClass]) -> None:
    pass

my_function_2(MyClass)    # Type checks
my_function_2(Child)      # Type checks
my_function_2(int)        # Does not type check
my_function_2(MyClass())  # Does not type check

Of course, the type checker won't be able to tell exactly which subtype you happen to be using within the functions themselves.

the type hint can only help when requiring value is a instance of certain type.

This is actually not something you can do. It is impossible to construct a type hint that asserts some value must be exactly one type and never any subtypes of that type (though you can often simulate something close-ish by using generics).

A type hint always indicates that some value is either an instance of that type or some subtype.

And the relevant documentation is really poor.

You may find reading the mypy docs to be useful, if you haven't found them already.

Mypy is a PEP 484 compliant static type checker, and was developed in parallel with PEP 484 itself. (Eg the core mypy devs were the ones who wrote PEP 484 and several other typing-related PEPs.)

The upshot is that the docs for mypy are generally more helpful than the official Python docs for typing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM