将lambda函数类型化为函数参数

时间:2017-09-07 21:16:12

标签: python python-2.7 python-3.x type-hinting

我有一个接受lambda的函数:

def my_function(some_lambda):
  # do stuff
  some_other_variable = some_lambda(some_variable)

my_function(lambda x: x + 2)

我想输入传递的lambda函数。

我已经尝试了

def my_function(some_lambda: lambda) -> None:
# SyntaxError: invalid syntax
from typing import Lambda
# ImportError: cannot import name 'Lambda'

我的IDE在2.7跨式类型提示上抱怨类似的事情,例如

def my_function(some_lambda: lambda) -> None:
  # type: (lambda) -> None
# formal parameter name expected

2 个答案:

答案 0 :(得分:6)

当你想到这一点时很明显,但是需要一段时间才能注册。 lambda是一个函数。没有函数类型,但Callable包中有typing类型。这个问题的解决方案是

from typing import Callable
def my_function(some_lambda: Callable) -> None:

Python 2版本:

from typing import Callable
def my_function(some_lambda):
  # type: (Callable) -> None

答案 1 :(得分:0)

Callable是您问题的答案。

def GroupOfProduct(request):
    related_ids = request.POST.getlist('relatedid')
    product_ids = request.POST.getlist("product")

    # delete the existing ProductRelatedGroupAndProduct entries
    for product_id in related_ids:
        product = Product.objects.filter(id=product_id).first()
        obj = ProductRelatedGroupAndProduct.objects.get(product = product)
        obj.delete()

    # create new records in ProductRelatedGroupAndProduct with the selected product_ids
    for product_id in product_ids:
        product = Product.objects.filter(id=product_id).first()
        obj = ProductRelatedGroupAndProduct(
            product = product,
        )
        obj.save()