0

I'm struggling with the following piece of code:

def function(param):
    if(param == 'notgen'):
        return 'some text'
    elif(param == 'gen'):
        for x in range(10):
            yield x
gen = function('notgen')
print(type(gen))
>>> <class 'generator'>

I suppose, this is expected behavior, but I cannot find proper docs. I need to yield and return values from one function depending on the situation. Is it even doable?

Thanks everybody for suggestions!

georg
  • 211,518
  • 52
  • 313
  • 390
holoubekm
  • 29
  • 2
  • Believe so. I want to force the function once behave like a generator and second time like a function with return value. – holoubekm Jul 21 '17 at 14:02
  • or loop on the result `for i in function('notgen')` – Jean-François Fabre Jul 21 '17 at 14:03
  • I disagree with the duplicate target @georg. The target you linked to only address how `return` and `yield` were handled in the same function. But that doesn't seem to be what the OP is confused about. It never explained how regardless of where `yield` is put in a function, Python will always make the function a generator. – Christian Dean Jul 21 '17 at 14:13
  • @ChristianDean: the OP seems to expect their `return` to actually return a value, the duplicate explains why this is not going to work in a generator. – georg Jul 21 '17 at 14:19
  • Exactly! Maybe my description was a bit misleading. I want to force the function to behave differently depending on the parameter. For now, it seems to be just matter of presence of the yield keyword. – holoubekm Jul 21 '17 at 14:19
  • @georg Alright, I guess I see your point. – Christian Dean Jul 21 '17 at 14:21

0 Answers0