简体   繁体   中英

type hint for class type as argument

In the python client library of ros2 there is a function that accepts the class type as an argument (not an instance of that class, but the definition).

For example

from std_msgs.msg import String
#String is python class i.e,
#class String:
#    ...

class MyNode(Node)
    def __init__(self):
        super().__init__('my_node')
        self.add_subscription(String, 'chatter', lambda msg : print(msg))
        #Note that we pass in the type String, not an object, i.e String()

How could something like this be annotated using the python type annotations?

One way would be to use the Executable type hint, as the class type can be called with () to construct an object. But this doesn't convey it's true meaning very well.

def foo(class_type: Executable):
   obj: Any = class_type()

It would be better if there was something like:

def foo(class_type: Class):
   object: Any = class_type()

Is there anything like this? What is the standard way to do this?

Ideally I would like this to work with the MyPy static type check system.

There is actually a type hint for what you want, it is just calledType instead of Class .

As you can also see, you can tell it what it should be a class of, so in the example you gave it would be:

Type[String]

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