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 8545163
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T12:43:49+00:00 2026-06-11T12:43:49+00:00

Let’s say I have a class class Foo: def __init__(self): pass def meth1(self, *args):

  • 0

Let’s say I have a class

class Foo:
    def __init__(self):
        pass
    def meth1(self, *args):
        do_stuff()
    def meth2(self, **kwargs):
        more_stuff()
    def callme(self):
        print "I'm called!"

and I want to smartly modify it so that callme() is called after executing meth1, meth2 and everything else. How do I do that? I’ve never used either class decorators or metaclasses, so I’m not sure which is the way to go and also how to use them properly.

With metaclasses, I’ve put together the following:

from types import FunctionType
def addcall_meta(name, bases, dct):
    newdct = dict(dct)
    for k, v in dct.items():
        if isinstance(v, FunctionType) and k not in ('__metaclass__', 'callme'):
            # the above can include more filters such as not startswith, etc.
            print k, 'is a function!'
            def newmethod(self, *args, **kwargs):
                v(self, *args, **kwargs)
                dct['callme'](self)
            newdct[k] = newmethod
    return type(name, bases, newdct)

With a class decorator:

def addcall_deco(cls):
    dct = {}
    for k, v in cls.__dict__.items():
        if isinstance(v, FunctionType) and k != 'callme':
            def newv(self, *args, **kwargs):
                v(self, *args, **kwargs)
                self.callme()
            cls.k = newv
    return cls

Both seem to work for my super-simple example:

In [75]: Foo()
I'm called!
Out[75]: <__main__.Foo instance at 0x21ed680>

Are there obvious reasons to use one and not the other (such as specific corner cases, etc.)? I also figure I could somehow use __new__, but from the common-sense point of view, I want to modify the class, not all of its instances.

  • 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-11T12:43:51+00:00Added an answer on June 11, 2026 at 12:43 pm

    Actually you are using your metaclass as a class decorator here – not really needing the more flexible things that are allowed with metaclasses.

    Therefore, both implementations being the same, you should go witht he simpler approach – which is class decorators. As for “backwards compatibility” – it is not an issue you should worry about in a new project.

    Of course, a lot of servers out there are running some very old Linuxes due to “long term support” editions, and feature Python versions as old as 2.4 or 2.5 – but if
    your project is indeed being used in such an older server, the user can always install an updated enough to be supported Python as a normal user – no need to use the system Python.

    On a side note: beware on your wrapper that you are discarding the wrapped method return value, if there is any. The way to do it is:

     def newv(self, *args, **kwargs):
          result = v(self, *args, **kwargs)
          self.callme()
          return result
    

    And finally, if you think you will need this kind of approach a lot on any project you are dealing with, take a look at “Aspect Oriented Programing” – There are a couple of projects out there that allow an aspected oriented approach in Python without many changes in your toolchain or way of working.

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

Sidebar

Related Questions

Let me explain best with an example. Say you have node class that can
Let's say on a page I have alot of this repeated: <div class=entry> <h4>Magic:</h4>
Let's say I have the following classes : public class MyProductCode { private String
Let's say you have a class called Customer, which contains the following fields: UserName
Let's say you have a class, with certain properties, and that you tried your
Let's say I had a model that looked something like this: class SomeModel def
Let's say I have a JAR xxx-core.jar with the following classes: @XmlRootElement @XmlSeeAlso({Imp1.class, Imp2.class})
Let's say I have the string: hello world; some random text; foo; How could
Let's say I don't have photoshop, but I want to make pattern files (.pat)
Let's say I have a method in java, which looks up a user in

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.