#weird wrapped function behaviour

1 messages · Page 1 of 1 (latest)

cursive osprey
#

why does

        # dynamically add the event listeners
        def _create_event_listener(event: str):
            async def _event(*args):
                # do stuff
                print(event)

            return _event
        
        for event in self.events:
            bot.add_listener(_create_event_listener(event))
```work as expected but
```py
        for event in self.events:

            async def _event(*args):
                # do stuff
                print(event)

            bot.add_listener(_event, event)
``` not?

What is the difference between the two?

First example prints the right event name, when the event occurs and second example prints always the name of the last event in self.events, but on every event in self.events...

I found out that it's not just the name of the last event, but the full function. So in the second example, on every event in self.events, the function created in the last iteration of the loop is used. Why?
cursive osprey
#

anyone?