Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8161005
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T18:24:23+00:00 2026-06-06T18:24:23+00:00

I am new to python decorators. I have understood the basic concepts with the

  • 0

I am new to python decorators. I have understood the basic concepts with the help of simple examples. But when I tried to read this more practical decorator, I feel lost. Given below is the code followed by my questions:

class countcalls(object):
   "Decorator that keeps track of the number of times a function is called."

   __instances = {}

   def __init__(self, f):
      self.__f = f
      self.__numcalls = 0
      countcalls.__instances[f] = self

   def __call__(self, *args, **kwargs):
      self.__numcalls += 1
      return self.__f(*args, **kwargs)

   def count(self):
      "Return the number of times the function f was called."
      return countcalls.__instances[self.__f].__numcalls

@countcalls
def f():
   print 'f called'

f()
f()
f()
print f.count() # prints 3

My doubts:

  1. When we prefix the decorator to a function, does that mean that we are creating an object of the decorator class right there? In our case, when it says:

    @countcalls
    def f():
    print 'f called'

Is @countcalls equivalent to creating a countcalls object and passing the function below to its __init__ method?

  1. The __call__ is taking three arguments. self is fine as far as the question above is answered. What the hell are the two other arguments: *args, **kwargs and what are they achieving?

  2. How can I get better at decorators?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T18:24:24+00:00Added an answer on June 6, 2026 at 6:24 pm

    This code seems to have some oddness. Let’s talk about the slightly-simpler code

    class countcalls(object):
    
        def __init__(self, f):
            self._f = f
            self._numcalls = 0
    
        def __call__(self, *args, **kwargs):
            self._numcalls += 1
            return self._f(*args, **kwargs)
    
        def count(self):
            return self._numcalls
    
    @countcalls
    def f():
        print 'f called'
    
    f()
    f()
    f()
    print f.count() 
    
    # output:
    #   f called
    #   f called
    #   f called
    #   3
    

    Remember

    @countcalls
    def f():
        print 'f called'
    

    is the same thing as

    def f():
        print 'f called'
    f = countcalls(f)
    

    so when we use the decorator, the function is stored using the _f attribute.

    So f is a countcalls instance. When you do f(...) you call f.__call__(...)—that’s how you implement () syntax for your own instances. So when you call f, what happens?

        def __call__(self, *args, **kwargs):
            self._numcalls += 1
            return self._f(*args, **kwargs)
    

    First, you use *args and **kwargs, which in the definition condense all positional and keyword arguments into a tuple and dict, and later in the call expand a sequence and a dict into arguments (see 4.7.4 in the official tutorial for more information). Here’s a partial example

    >>> def f(*args): print args
    ... 
    >>> f(1, 2)
    (1, 2)
    >>> f()
    ()
    >>> def add(a, b): return a + b
    ... 
    >>> add(*[4, 3])
    7
    >>> add(**{'b': 5, 'a': 9})
    14
    

    so def f(*args, **kwargs): return g(*args, **kwargs) just does a passthrough on all arguments.

    Aside from that, you’re just keeping track of how many times you’ve been in __call__ for this instance (how many times you’ve called f).

    Just remember that @dec def f(...): ... is the same as def f(...): ... f = dec(f) and you should be able to figure out most decorators fine, given enough time. Like all things, practice will help you do this quicker and easier.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

New to Python, have a simple, situational question: Trying to use BeautifulSoup to parse
Very new to python and can't understand why this isn't working. I have a
Brand new to Python (and programming in general), if this is simple and/or answered
I am new python programmer,what I have understood so far,yield keyword returns an object
I am new to Python and have been studying its fundementals for 3 months
I'm a new to Python. I have installed Python 2.7 64 bit on Win7
Python 2.5.4. Fairly new to Python, brand new to decorators as of last night.
So I'm still kind of new to Python decorators - I've used them before,
Is there a way to combine two decorators into one new decorator in python?
I am new to python, I have changed my path to point to the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.