← index #8614Issue #2184
Related · high · value 0.164
QUERY · ISSUE

Can't distinguish generator type from coroutine type in esp32 Micropython 1.17

openby joaduoopened 2022-05-03updated 2022-05-03
py-core

While doing a little personal webserver framework I wanted to be able to distinguish coroutines from generators

Here hypothetical use cases:

@app.plain()
def log_table(verb, cfg):
    # Here we do a generator to avoid out of memory problems
    for r in solar_log.measurements:
        yield '{}'.format(r)

@app.json(is_async=True)
async def solarcfg(verb, cfg):
    # Here we do an async method to call async functions
    if verb == POST:
        resp = await solar.set_config(cfg)
    else:
       resp = await solar.get_config()
    return resp

Right now I am solving this by adding an argument to the decorator @app.json(is_async=True), but I would like to avoid such thing and directly distinguish between coroutines and generators types. (in order to know when to iterate and when to await)

The following code:

import uasyncio

def test_generator():
    yield 1

async def test_coroutine():
    return 1

print(type(test_generator()))
print(type(test_coroutine()))
print(type(test_generator()) == type(test_coroutine()))

Outputs this:

>>> %Run -c $EDITOR_CONTENT
<class 'generator'>
<class 'generator'>
True

Is there another workaround (other than explicitly stating it in the decorator) to distinguish those types?

Thanks

CANDIDATE · ISSUE

unix: type of generator function is incorrect

closedby peterhinchopened 2016-06-14updated 2016-07-01

MicroPython seems unable to distinguish a generator function from a generator:

def foo(x):
     while x > 0:
         yield x
         x -= 1

This correctly produces the following under cPython 3.4.3

>>> bar = foo(5)
>>> type(foo)
<class 'function'>
>>> type(bar)
<class 'generator'>
>>> 

Under MicroPython v1.7-305-g56fd33a-dirty on 2016-05-03; linux version

>>> bar = foo(5)
>>> type(bar)
<class 'generator'>
>>> type(foo)
<class 'generator'>
>>> type(foo) is type(bar)
False
>>> 

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied