Function type in Python

UPD: Function type in Python is types.FunctionType.

Running in the Python interactive interpreter this:

def spam():
    pass

print(type(spam))

produces:

builtins.function

The function type is builtins.function, quite logically.

Now, consider the following code you want to annotate:

def spam():
    def eggs():
        pass

    return eggs

How do we annotate the type of the output function spam?

Well, the first thing to try is:

def spam() -> builtins.function:
    def eggs():
        pass

    return eggs

Which is the wrong answer. Your code will crash with a NameError, because there’s no builtins.function declared.

Using function, __builtin__.function, from builtins import function, and import builtins.function won’t help.

So, what to do?

For example, this:

def spam() -> type(lambda: _):
    def eggs():
        pass

    return eggs

In fact, this is a pretty good solution; it’s clear and easy to understand. In addition, nothing better came to me anyway.


Interesting fact: Visual Studio with the (awesome) Python Tools 2.0 crashes as soon as it meets this code. No, really, try it yourself. Create a file with type(lambda: _) and open it in VS with PTVS 2.0 installed.

UPD: Fixed in PTVS 2.1 Beta.

 
6
Kudos
 
6
Kudos

Now read this

Multi-Language Documentation in Reverse

Note: This is a longer version of my lighting talk and Write the Docs EU 2014. Delivering content in many languages is great. It’s also quite resource consuming. So, you have to decide what really needs multi-language support and what... Continue →