5 kyu

Context manager decorator

Description
Loading description...
Fundamentals
  • Please sign in or sign up to leave a comment.
  • trashy_incel Avatar

    the link in the description points to the docs for Python 2.7, which is quite ancient. it should be upgraded to more recent docs

  • niko13 Avatar

    Hello There, i am trying to do this kata but get stuck on when the with statement is executed

    i am not able to get to the enter method, even if i do my custom contextmanager...

    is there any tips you can provide ?

  • Voile Avatar

    The initial code for the kata is this:

    def contextmanager(f):
        def wrapper(*args, **kwargs):
            # your solution
        return wrapper
    

    which is misleading and wrong: context manager is only used as @contextmanager so wrapper should not have any arguments. The actual parameters are passed in later to the thing returned from the wrapper.

    • Dundee Avatar

      You are probably mixing together decorator taking args and not taking args. You would be right, if contextmanager would be called as a function, like this:

      def some_decorator(some_arg=None):
          def inner(func):
              def wrapper(*args, **kwargs):
                  ...
                  return func(*args, **kwargs)
              return wrapper
          return inner
      
      @some_decorator()  # note the parentheses
      def foo(x):
          print(x)
      
      foo('aaa')
      

      However, you have to take args and kwargs in the wrapper if you use the decorator without args:

      def some_decorator(func):
          def wrapper(*args, **kwargs):
              ...
              return func(*args, **kwargs)
          return wrapper
      
      @some_decorator  # no parentheses
      def foo(x):
          print(x)
      
      foo('aaa')
      
      Issue marked resolved by Dundee 4 years ago
  • Voile Avatar

    This kata needs random tests.

  • askurandrio Avatar

    This comment has been hidden.

  • andre-dasilva Avatar

    Really nice kata. would be nice if there were more test cases

  • Unnamed Avatar

    This comment has been hidden.

  • zellerede Avatar

    There could be more test cases, at least for nonempty function arguments.

  • adam-tokarski Avatar

    Thanks for this Kata. It's good to be aware of these possibilities!

  • minus7 Avatar

    This comment has been hidden.