4 ms·
There are two cases to consider. One is where the closure is called multiple times. This is the "by necessity" case, because the enclosed definition is executab
by blattimwind 8y ago
There are two cases to consider. One is where the closure is called multiple times. This is the "by necessity" case, because the enclosed definition is executable and Python must make believe that this definition is re-executed every time the function is called.
If you are just calling the enclosed function then of course this does not happen. Compare:
def mytype():
print("!")
return dict()
def closure():
def enclosed(x: mytype()):
pass
return enclosed
print("Calling the closure")
for i in range(10):
closure()
print("Calling the enclosed")
f = closure()
for i in range(10):
f(0)
Note that using closures is almost always faster in Python than classes, because accesses to enclosed variables are done through offsets instead of attribute lookup (this gap has been somewhat closed, but is still significant in some cases; arguably almost all of these cases indicate that you are using either the wrong language, or the wrong implementation). So adding overhead to closures can be a somewhat valid reason to avoid using these annotations.