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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T17:07:35+00:00 2026-06-01T17:07:35+00:00

I want to apply the same decorator to every method in a given class,

  • 0

I want to apply the same decorator to every method in a given class, other than those that start and end with __.

It seems to me it should be doable using a class decorator. Are there any pitfalls to be aware of?

Ideally, I’d also like to be able to:

  1. disable this mechanism for some methods by marking them with a special decorator
  2. enable this mechanism for subclasses as well
  3. enable this mechanism even for methods that are added to this class in runtime

[Note: I’m using Python 3.2, so I’m fine if this relies on features added recently.]

Here’s my attempt:

_methods_to_skip = {}

def apply(decorator):
  def apply_decorator(cls):
    for method_name, method in get_all_instance_methods(cls):
      if (cls, method) in _methods_to_skip:
        continue
      if method_name[:2] == `__` and method_name[-2:] == `__`:
        continue
      cls.method_name = decorator(method)
  return apply_decorator

def dont_decorate(method):
  _methods_to_skip.add((get_class_from_method(method), method))
  return method

Here are things I have problems with:

  • how to implement get_all_instance_methods function
  • not sure if my cls.method_name = decorator(method) line is correct
  • how to do the same to any methods added to a class in runtime
  • how to apply this to subclasses
  • how to implement get_class_from_method
  • 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-01T17:07:37+00:00Added an answer on June 1, 2026 at 5:07 pm

    I think this is better done with a metaclass, in order to handle both runtime and subclass method decoration. I don’t see an elegant way to handle subclasses automatically with a class decorator.

    from types import FunctionType
    
    # check if an object should be decorated
    def do_decorate(attr, value):
        return ('__' not in attr and
                isinstance(value, FunctionType) and
                getattr(value, 'decorate', True))
    
    # decorate all instance methods (unless excluded) with the same decorator
    def decorate_all(decorator):
        class DecorateAll(type):
            def __new__(cls, name, bases, dct):
                for attr, value in dct.iteritems():
                    if do_decorate(attr, value):
                        dct[attr] = decorator(value)
                return super(DecorateAll, cls).__new__(cls, name, bases, dct)
            def __setattr__(self, attr, value):
                if do_decorate(attr, value):
                    value = decorator(value)
                super(DecorateAll, self).__setattr__(attr, value)
        return DecorateAll
    
    # decorator to exclude methods
    def dont_decorate(f):
        f.decorate = False
        return f
    

    And an example of its use (Python 2, but trivially modified for Python 3):

    def printer(f):
        print f
        return f
    
    class Foo(object):
        __metaclass__ = decorate_all(printer)
        def bar(self):
            pass
        @dont_decorate
        def baz(self):
            pass
        @classmethod
        def test(self):
            pass
    # prints
    # <function bar at 0x04EB59B0>
    
    class AnotherName(Foo):
        def blah(self):
            pass
    # prints
    # <function blah at 0x04EB5930>
    
    Foo.qux = lambda: 1
    # prints
    # <function <lambda> at 0x04EB57F0>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to apply right alignment on the last cell of every table row,
I want to apply some CSS to text that I can't get marked up
I have a long-running process that must run every five minutes, but more than
I have a List called myData and I want to apply a particular method
I want to apply the rules in a CSS file to a certain div/class
I have a div that i want to apply two backgrounds to it. Basically
I am working on PowerPoint macro. In that I want to apply theme programatically
I have a class extends ViewGroup and want to get every MotionEvent from it.
I want to apply one autocomplete extender for multiple textbox having same name attribute,
I have two elements, I want to apply same background style, but different font

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.