Проверка типа генератора методов - PullRequest
1 голос
/ 01 июля 2019

У меня есть функция, которая принимает другую функцию в качестве аргумента. Я хочу проверить, является ли аргумент обычной функцией или генератором.

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

Метод класса выглядит следующим образом

MyClass:

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

Есть ли способ проверить, является ли метод класса генератором или функцией?

Ответы [ 2 ]

1 голос
/ 01 июля 2019

вызовите вашу функцию:

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])) // <------
0 голосов
/ 01 июля 2019

Способ сделать это - использовать скрытый атрибут .__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")

Это углубится в функцию, а не просто скажет, что это метод класса.

...