Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: "NameError: name 'function' is not defined"

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'>.

like image 654
qwertz Avatar asked Dec 19 '22 04:12

qwertz


1 Answers

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).

like image 84
Martijn Pieters Avatar answered Dec 20 '22 21:12

Martijn Pieters