check if object is a generator

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
ttmetro
Posts: 104
Joined: Mon Jul 31, 2017 12:44 am

check if object is a generator

Post by ttmetro » Fri Nov 16, 2018 9:57 pm

How do I check if an object is a coroutine (generator) in micropython?

Code: Select all

from inspect import iscoroutine
is not available.

This appears to work, but (???):

Code: Select all

def iscoroutine(obj):
    return str(type(obj)) == "<class 'generator'>"
Bernhard Boser

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: check if object is a generator

Post by pythoncoder » Sat Nov 17, 2018 7:12 am

Code: Select all

type_gen = type((lambda: (yield))())
Test with

Code: Select all

isinstance(callback, type_gen)
It's sometimes also necessary to test for a generator function:

Code: Select all

type_gen = type((lambda: (yield))())  # Generator type
type_genf = type((lambda: (yield)))  # Generator function

def foo():
    for x in range(5):
        yield x

isinstance(foo, type_gen)  # False
isinstance(foo, type_genf)  # True

foo_gen = foo()
isinstance(foo_gen, type_gen)  # True
isinstance(foo_gen, type_genf)  # False
Peter Hinch
Index to my micropython libraries.

ttmetro
Posts: 104
Joined: Mon Jul 31, 2017 12:44 am

Re: check if object is a generator

Post by ttmetro » Mon Nov 19, 2018 7:37 pm

Thanks, works perfect!
Bernhard Boser

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: check if object is a generator

Post by pythoncoder » Tue Nov 20, 2018 6:12 am

I should acknowledge my debt to @pfalcon here.
Peter Hinch
Index to my micropython libraries.

Post Reply