Python: ContextManager-like for function alias
Question: ContextManager is really useful and it's also make our code more readable, but
it seems it only works if the given function is meant to be a context manager,
otherwise it will fail (no `__exit__` or something else). I' wondering if we
can use any function including those in libraries such as Django as a
contextmanager, suppose the given code

    
    
    self.assertEqual(Transaction.objects.filter(account=a, date=b, year=c).count(), 10)
    self.assertEqual(Transaction.objects.filter(account=e, date=f, year=g).count(), 15)
    self.assertEqual(Transaction.objects.filter(account=h, date=i, year=j).count(), 20)
    

Can be transformed into:

    
    
    with Transaction.objects.filter as f:
        self.assertEqual(f(account=a, date=b, year=c).count(), 10)
        self.assertEqual(f(account=d, date=d, year=e).count(), 15)
        self.assertEqual(f(account=h, date=i, yearj).count(), 20)
    

The way I look at it is that the one below is much readable, cleaner and less
verbose. Is this possible?


Answer: Just do:

    
    
    f = Transaction.objects.filter
    

before your statements!

If you really wanted to use a context manager, you could write one that does
what you want:

    
    
    from contextlib import contextmanager
    
    @contextmanager
    def alias(func):
        yield func
    
    with alias(Transaction.objects.filter) as f:
        ...
    

Note that, however you do this, without an explicit `del` statement, `f` will
still be around after the `with`.

