Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generator behaviour
#1
Hello,

encountered this smart piece of breadth-first traversal:

def bfs(root):
    yield root
    for n in bfs(root):
        yield n.left
        yield n.right
but am confused about pythons behaviour here.

If you omit the first yield, the (recursive?) generator call on line 3 is
empty and this results in endless recursion, so behaves like a function
call. (One would expect it to not get executed at all).

But with the first yield, the non-empty generator gets iterated over.
Looks like the call behaves like a function in one case and a generator in
the other?
Reply


Messages In This Thread
Generator behaviour - by bla123bla - Jul-20-2022, 09:11 PM
RE: Generator behaviour - by deanhystad - Jul-21-2022, 04:42 AM
RE: Generator behaviour - by bla123bla - Jul-26-2022, 07:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyevent counterintuitive behaviour ZazaRy 1 569 Dec-29-2024, 02:10 PM
Last Post: deanhystad
  logger behaviour setdetnet 1 1,526 Apr-15-2023, 05:20 AM
Last Post: Gribouillis
  can someone explain this __del__ behaviour? rjdegraff42 1 1,202 Apr-12-2023, 03:25 PM
Last Post: deanhystad
  Asyncio weird behaviour vugz 2 2,782 Apr-09-2023, 01:48 AM
Last Post: vugz
  Weird behaviour using if statement in python 3.10.8 mikepy 23 7,545 Jan-18-2023, 04:51 PM
Last Post: mikepy
  Inconsistent behaviour in output - web scraping Steve 6 4,076 Sep-20-2021, 01:54 AM
Last Post: Larz60+
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 3,919 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  Behaviour of 2D array SimonB 6 3,995 Jan-21-2021, 01:29 PM
Last Post: SimonB
  strange behaviour- plotting nathan_Blanc_Haifa 0 1,916 Dec-27-2020, 01:37 PM
Last Post: nathan_Blanc_Haifa
  OOP behaviour problem JohnB 3 3,197 Aug-18-2020, 07:51 PM
Last Post: JohnB

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020