'Return formatted representation of a type annotation.
Show qualified names for types and additional details for types from
the ``typing`` module.
Displaying complex types from ``typing`` relies on its private API.'

def format_annotation(self, annotation):

    if isinstance(annotation, string_types):
        return annotation
    if isinstance(annotation, typing.TypeVar):
        return annotation.__name__
    if (annotation == Ellipsis):
        return '...'
    if (not isinstance(annotation, type)):
        return repr(annotation)
    qualified_name = (((annotation.__module__ + '.') + annotation.__qualname__) if annotation else repr(annotation))
    if (annotation.__module__ == 'builtins'):
        return annotation.__qualname__
    elif isinstance(annotation, typing.GenericMeta):
        params = None
        if hasattr(annotation, '__args__'):
            if ((annotation.__args__ is None) or (len(annotation.__args__) <= 2)):
                params = annotation.__args__
            else:
                args = ',    '.join((self.format_annotation(arg) for arg in annotation.__args__[:(-1)]))
                result = self.format_annotation(annotation.__args__[(-1)])
                return ('%s[[%s],    %s]' % (qualified_name, args, result))
        elif hasattr(annotation, '__parameters__'):
            params = annotation.__parameters__
        if (params is not None):
            param_str = ',    '.join((self.format_annotation(p) for p in params))
            return ('%s[%s]' % (qualified_name, param_str))
    elif (hasattr(typing, 'UnionMeta') and isinstance(annotation, typing.UnionMeta) and hasattr(annotation, '__union_params__')):
        params = annotation.__union_params__
        if (params is not None):
            param_str = ',    '.join((self.format_annotation(p) for p in params))
            return ('%s[%s]' % (qualified_name, param_str))
    elif (isinstance(annotation, typing.CallableMeta) and (getattr(annotation, '__args__', None) is not None) and hasattr(annotation, '__result__')):
        args = annotation.__args__
        if (args is None):
            return qualified_name
        elif (args is Ellipsis):
            args_str = '...'
        else:
            formatted_args = (self.format_annotation(a) for a in args)
            args_str = ('[%s]' % ',    '.join(formatted_args))
        return ('%s[%s,    %s]' % (qualified_name, args_str, self.format_annotation(annotation.__result__)))
    elif (isinstance(annotation, typing.TupleMeta) and hasattr(annotation, '__tuple_params__') and hasattr(annotation, '__tuple_use_ellipsis__')):
        params = annotation.__tuple_params__
        if (params is not None):
            param_strings = [self.format_annotation(p) for p in params]
            if annotation.__tuple_use_ellipsis__:
                param_strings.append('...')
            return ('%s[%s]' % (qualified_name, ',    '.join(param_strings)))
    return qualified_name
