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

7 улучшений для Ульяновска

Я живу в Ульяновске, в общем-то, всю жизнь, почти 28 лет, и пока не планирую отсюда уезжать. Поэтому меня остро волнует судьба города. Хочу, чтобы он был комфортным для меня, моей семьи и горожан. На 2016 год надо признать, что Ульяновск... Continue →