How to recognize a generator function?

Brandon Beck bbeck at NOSPAM.austin.rr.com
Wed Jun 18 17:30:01 EDT 2003


This isn't perfect, and you should probably constrain the exception
handlers and consider what happens if the function or generator throws
an exception itself, but it should suffice to illustrate one possible
direction for you to take.  There is also some potentially awkward
behavior that could come about if you pass in a function that has a
function named next on it.

def call(obj):
    try:
        obj()
        return
    except:  # Wasn't a generator function
        pass

    try:
        obj.next()
        return
    except:
        pass

    # Try anything any other ways you want to "call" here...

    raise Exception("I don't know how to handle: %s" % (obj,))



Brandon



> I'll try to explain me better. Supose :
>
> # a generator-function
> def f():
>   a = 1
>   yield a
>
> # a kind of callback
> def call( object )
>   if isGeneratorfunction( object):
>       g = object()
>   elif Type(object) is GeneratorType:
>       object.next()
>
> call( f )






More information about the Python-list mailing list