检查方法生成器的类型

时间:2019-07-01 09:46:05

标签: python python-3.x types generator

我有一个函数,需要另一个函数作为参数。我希望它检查参数是常规函数还是生成器。

import types

def my_func(other_func):
    if isinstance(other_func, types.GeneratorType):
        # do something
    elif isinstance(other_func, types.FunctionType):
        # do something else
    else:
        raise TypeError(f"other_func is of type {type(other_func)} which is not supported")

但是问题在于该函数是一个类方法,所以我得到以下信息:

other_func is of type <class 'method'> which is not supported

class方法看起来像这样

MyClass:

    def other_func(self, items):
        for item in items:
            yield item

有什么方法可以检查类方法是生成器还是函数?

2 个答案:

答案 0 :(得分:1)

调用函数:

c = MyClass() 
my_func(c.other_func([1,2,3])) 

完整代码:

import types

def my_func(other_func):
    if isinstance(other_func, types.GeneratorType):
        # do something
        print ("test1")
    elif isinstance(other_func, types.FunctionType):
        # do something else
        print("test2")
    else:
        raise TypeError(f"other_func is of type {type(other_func)} which is not supported")


class MyClass:
    def other_func(self, items):
        for item in items:
            yield item

c = MyClass() // <------
my_func(c.other_func([1,2,3])) // <------

答案 1 :(得分:0)

执行此操作的方法是使用.__func__隐藏属性,如下所示:

import types

def my_func(other_func):
    if isinstance(other_func.__func__(other_func.__self__), types.GeneratorType):
        # do something
    elif isinstance(other_func.__func__(other_func.__self__), types.FunctionType):
        # do something else
    else:
        raise TypeError(f"other_func is of type {type(other_func)} which is not supported")

这将对功能进行更深入的研究,而不仅仅是说它是一个类方法。