3

I am trying to use python3 type annotation features.

Here is some toy functions without annotation:

def fa(func, *args):
    return func(*args)
def fb(x:str):
    return x + " returned."
fa(fb, "Newton")

These work ok. But once I add some annotation for fa, it goes awry:

def fa(func:function, *args):
    return func(*args)
def fb(x:str):
    return x + " returned."
fa(fb, "Newton")

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/IPython/core/interactiveshell.py", line 2883, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-17-193b74f82e47>", line 1, in <module>
    def fa(func:function, *args):
NameError: name 'function' is not defined

Why is this happening and how can I work around it?

qed
  • 22,298
  • 21
  • 125
  • 196

3 Answers3

7

As the error message tells you, the name function isn't defined. If you want to hint as a function, put it in quotes:

def fa(func: 'function', *args):
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

As the error message tells you, the name function isn't defined. If you want to hint as a function, put it in quotes:

def fa(func: 'function', *args):

Besides what @johnrsharpe says you can also include the following line at the top of your python script if you don't want to qoute the name function

# from __future__ imports must occur at the beginning of the file. DO NOT CHANGE!
from __future__ import annotations
Ayush
  • 457
  • 8
  • 16
-1

Because you define a variable in function parameters,but that parameter is not exist out of function.You have to write

fa(function="Newton")

GLHF
  • 3,835
  • 10
  • 38
  • 83