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

Adding trees to random terrains in Enu 0.2

Read the first part In this tutorial, I’ll add some trees to the random terrain that we’ve created last time. For the impatient, here is the complete code: https://gist.github.com/moigagoo/d40a76beee5a62d2fec7679ebc033730 As before, let... Continue →