Hammerite
Hammerite

Reputation: 22350

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

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

Upvotes: 4

Views: 1044

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799240

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.

Upvotes: 3

Related Questions