8

Running

def foo(bar: function):
    bar()

foo(lambda: print("Greetings from lambda."))

with Python 3.6.2 yields

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined

However, removing the type annotation works as expected.

PyCharm additionally gives the warning 'function' object is not callable on line bar().


edit: As stated in my comment of Pieters’ answer, this question raised, because

def myfunction():
    pass

print(myfunction.__class__)

outputs <class 'function'>.

qwertz
  • 14,614
  • 10
  • 34
  • 46

2 Answers2

17

There is no name function defined in Python, no. Annotations are still Python expressions and must reference valid names.

You can instead use type hinting to say bar is a callable; use typing.Callable:

from typing import Any, Callable

def foo(bar: Callable[[], Any]):
    bar()

This defines a callable type that takes no arguments and whose return value can be anything (we don't care).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 7
    Thanks, I was expecting it to be valid, because checking a functions class, via `print(myfunction.__class__)` yields ``. – qwertz Sep 11 '17 at 20:20
  • 1
    @qwertz: sure, but that doesn't mean that there is a global name `function` referencing the type. – Martijn Pieters Sep 11 '17 at 20:20
0

Absolute Answer

from types import FunctionType as function

def foo(bar: function):
    bar()

foo(lambda: print("Greetings from lambda."))

print('-' * 30)
print(function)
print('type(foo) is function:', type(foo) is function)
print('type(foo) == function:', type(foo) == function)
print('function is foo.__class__:', function is foo.__class__)
print('function == foo.__class__:', function == foo.__class__)
print('callable(foo):', callable(foo))

Execution result: enter image description here

蔡宗容
  • 927
  • 12
  • 9