-1

The code below uses the context manager to ensure that the code 'set something up' and 'shut things down' is always executed. What I can't understand what role the yield keyword plays here and how the bar argument is declared.

@contextmanager
def function(foo):
    # set something up

    def nestedfunction(bar):
        # do something with bar
        pass

    try:
        yield nestedfunction
    finally:
        # shut things down

The function will be called as follows

reporter = function(foo)
leafystar
  • 129
  • 1
  • 1
  • 7
  • So you know what yield is and how to use? – Wonka Jul 23 '19 at 11:56
  • @Wonka I think I understand the use of the yield keyword in the context of a for loop returning a generator. I do not however understand the use of it here, where it returns a function object. – leafystar Jul 23 '19 at 12:52
  • So probably you are using yield when you can just use a return? – Wonka Jul 23 '19 at 12:54
  • I think I have solved my problem by being exposed to the idea of closures, this explained why no arguments have been passed https://www.geeksforgeeks.org/python-closures/ – leafystar Jul 24 '19 at 15:21
  • Have you looked at the docs for [`contextmanager`](https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager)? – Eric Jul 27 '19 at 19:36

1 Answers1

0

The function will be called as follows

reporter = function(foo)

This isn't true. It's a context manager, so would be used as:

with function(foo="foo") as reporter:
    reporter(bar="bar1")
    reporter(bar="bar2")
Eric
  • 95,302
  • 53
  • 242
  • 374