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

Generating random terrains in Enu 0.2

Enu is an interactive programming sandbox that helps learn programming through game creation. The author made it with children convenience in mind so it’s great for teaching kids programming. Just days ago, a long-awaited Enu 0.2 was... Continue →