What type in the typing module describes a class? What type describes a function?

前提是你 提交于 2021-02-07 19:16:06

问题


The new typing module in Python 3.5 provides a number of tools for use in type annotations. Does it provide an object or type that encapsulates the idea of class? How about the idea of function?

In the following code, which defines a decorator, what should stand in for class_? What should stand in for function? (typing.Callable is inadequate, because for example a class is callable, but the code is trying to identify methods.) (The no_type_check() decorator in the typing module itself might be a prototype for decorators that act like this. no_type_check() itself does not have any annotations, type-hint or otherwise.)

import typing

def is_double_underscore_name (name):
    return len(name) > 4 and name.startswith('__') and name.endswith('__')

# This code will not run, because 'class_' and 'function' are names that do not have any
# predefined meaning. See the text of the question.

# Note: This modifies classes in-place but (probably) does not modify functions in-place;
# this is not a considered design decision; it is just the easiest thing to do in a very
# basic example like this.
def do_something (class_or_function: typing.Union[class_, function]):
    if isinstance(class_or_function, class_):
        for name in class_or_function.__dict__:
            if not is_double_underscore_name(name):
                object = class_or_function.__dict__[name]
                if isinstance(object, function):
                    class_or_function.__dict__[name] = do_something(object)
        return class_or_function
    else:
        ... # return the function, modified in some way

回答1:


Classes are instances of the type type.

Functions are of the types types.FunctionType or types.BuiltinFunctionType.

Methods are of the types types.MethodType or types.BuiltinMethodType.

types has been a part of Python for... a very long time.



来源:https://stackoverflow.com/questions/34458848/what-type-in-the-typing-module-describes-a-class-what-type-describes-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!