Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function annotation in python 3 get "name not defined" error

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?

like image 670
qed Avatar asked Oct 17 '25 17:10

qed


1 Answers

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):
like image 154
jonrsharpe Avatar answered Oct 20 '25 06:10

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!