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

Одно кофе и псевдограмотность

Есть такие люди, которые любят поправлять другим людям речь. «Кофе — это он», «красивее, а не красивее», «звонят, а не звонят». Они делают это по разным причинам: кто-то просто тешит свое самолюбие, кто-то искренне пытается помочь.... Continue →