2
class fcount(object):
    def __init__(self, func):
            self.func = func
            self.count = 0
            self.context_count = 0
    def __enter__(self):
            self.context_count = 0
    def __call__(self, *args):
            self.count += 1
            self.context_count += 1
            return self.func(*args)
    def __exit__(self, exctype, value, tb):
            return False

This is a decorator. The idea is to keep a separate count when using a 'with' block.

If I do this:

@fcount
def f(n):
    return n+2

with fcount(foo) as g:
    print g(1)

I get this error: TypeError: 'NoneType' object is not callable

I tried printing out the type of g inside that with block, and of course the type is None.

Any idea why g isn't being assigned to fcount(foo)?

This does work:

g = fcount(foo)
with g:
    g(1)

1 Answer 1

2

You forgot to return the object from __enter__().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.