I've learned. I'll share.

November 11, 2008

Easy Python Decorators with the decorator decorator

Decorators in python are very powerful, but are often a pain to get right, especially when you want to pass arguments to the decorator. Typically, it involves defining a function in a function in a function, etc, up to 4 layers deep. Can we make it easier? What if we even made a decorator to make decorators?

Perhaps we could use it catch and log errors:

@decorator
def log_error(func, *args, **kargs):
   try:
       return func(*args, **kargs)
   except Exception, error:
       print "error occurred: %r" % error

@log_error
def blowup():
   raise Exception("blew up")

blowup() # this gets caught and prints the error

Or maybe we'd like to synchronize a function to make it thread-safe:

@decorator
def synchronized(lock, func, *args, **kargs):
    lock.acquire()
    try:
        return func(self, *args, **kargs)
    finally:
        lock.release()

missle_lock = thread.RLock()

@synchronized(missle_lock)
def launch_missiles():
    pass

Or we could even use arguments to do do some object __init__ trickery (something I've had to do when working with wxpython):

@decorator
def inherits_format(method, *args, **kargs):
    self, parent = args[:2]
    self.format = parent.format
    return method(*args, **kargs)

class Child:
    @inherits_format
    def __init__(self, parent):
        pass

class Parent:
    def __init__(self, format):
        self.format = format

format = object()
child  = Child(Parent(format))
assert child.format is format

If you've never worked python decorators, these are few examples of how powerful they are. But you'll probably never want to write your own because it can be a pain. If that's the case, then the decorator decorator is for you! Here's the code for it. It's a little tricky, but all you have to do is import it, slap @decorator before your decorator, make sure you call func(*args, **kargs), and you're all set. This is as easy as decorators can get.

Update: Dave left a comment and notified me that there is another, much more complete, implementation of the same idea at http://www.phyast.pitt.edu/~micheles/python/documentation.html. So, if you want a very complete module, go there. If you want something small and simple to cut and paste into your own code, use the following.

def decorator(decorator_func):
    decorator_expected_arg_count = decorator_func.func_code.co_argcount - 1
    if decorator_expected_arg_count:
        def decorator_maker(*decorator_args):
            assert len(decorator_args) == decorator_expected_arg_count, "%s expects %d args" % (decorator_func.__name__, decorator_expected_arg_count)

            def _decorator(func):
                assert callable(func), "Decorator not given a function.  Did you forget to give %r arguments?" % (decorator_func.__name__)

                def decorated_func(*args, **kargs):
                    full_args = decorator_args + (func,) + args
                    return decorator_func(*full_args, **kargs)

                decorated_func.__name__ = func.__name__
                return decorated_func
            return _decorator
        return decorator_maker
    else:
        def _decorator(func):
            def decorated_func(*args, **kargs):
                return decorator_func(func, *args, **kargs)

            decorated_func.__name__ = func.__name__
            return decorated_func
        return _decorator
    

56 comments:

  1. Hi,

    You might also want to check out Michele Simionato's decorator module. It's more heavyweight but preserves signature, docstrings, and does some other neat tricks.

    ReplyDelete
  2. synchronised decorator example does not work.
    Alain

    ReplyDelete
  3. Dave, thanks for the heads up. I've never seen that module before, and it looks very complete and nice. It's not the first time I've written something and shared it only to find that someone else has done a better job :).

    ReplyDelete
  4. Idiotic and additionally trusting people at the same time can be an obstacle, on aged and also fully grown folk assembled also will follow a complication. Age and also embryonic concern together. London house painting

    ReplyDelete
  5. yes, you can watch your Favorite Hallmark Channel series and movies on Hulu activation code roku. Hallmark channel also available on Fubo TV.

    ReplyDelete
  6. Thanks for this wonderfull content and information.hulu.com/activate

    ReplyDelete
  7. Thanks for this wonderfull content and information.hulu.com/activate

    ReplyDelete
  8. I am very interested in this article, Thank you so much for sharing such a article.hulu error code 94

    ReplyDelete
  9. Hulu Error Code 301 is a paid American based video-on-demand subscription service. People pay to activate their accounts but sometimes the wrong Hulu activate device process can cause errors which can result in unwanted delay in watching their favorite TV shows and Movies.

    ReplyDelete
  10. You can easily manage Hulu devices from your Hulu Account.In order to www.hulu.com/activate activation code, you will need to login to your account on the device you’re watching Hulu.

    ReplyDelete
  11. Wow, this is really interesting reading. I am glad I found this and got to read it. Great job on this content. I like it. bodrum rodos feribot

    ReplyDelete
  12. Hey dear, I'm Dipti very new to the city of joy Juhu Call Girls. I'm from Mumbai by origin south Indian. I'm working here for some MNC company and I'm all alone here in the city of joy. Well, I have heard that there are lots of things to see in the city of joy. Well, dear guys, I'm looking for some secret season. I'm staying in an apartment in Newtown and I'm looking out for some hot secret season so please who are interested contact me. I really want to attain someone who is very decent and understanding. I'm also available for out-call anytime. I really want to keep secrets and please don't share my pics keep things secret. Loyal people, please contact me let's have some fun tonight. Visit Our Web:- http://www.modelnight.net/escort-in-juhu.html

    ReplyDelete
  13. Thanks for this informative article. Nice example of code using decorators, but it's still not very serious. For those who want to master programming at a deeper level and start creating complex things, I recommend looking for posts on the programming language you are interested in on Instagram, in which experienced programmers will tell and show you step by step how to code in your chosen language. Found a lot of similar posts there and many of them had about 49k likes, which makes me think that their authors were using https://soclikes.com/buy-instagram-likes to buy likes.

    ReplyDelete
  14. Welcome to the party of my life here you will learn everything about me. custom patches

    ReplyDelete
  15. We GoAssignmentHelp is a team of experts professional academic writers who provide the best Online Assignment Writing Services with accounting assignment help - marketing assignment helpmarketing assignment help</a in australia for Now you can get professional writing help with all your academic writing easily!

    ReplyDelete
  16. I know this if off topic but I'm looking into starting my own blog
    and was curious what all is needed to get setup? I'm assuming having a blog like yours would cost
    a pretty penny? I'm not very internet smart so I'm not 100% positive. Any tips or advice would be greatly appreciated.

    Review my webpage - 강남안마

    (freaky)

    ReplyDelete
  17. This is a really too good post. This article gives truly quality and helpful information. I’m definitely going to look into it. Also, Check apex focus group reviews        

    ReplyDelete
  18. A house cleaning company in Al-Ahsa depends on the use of the latest modern and advanced methods and methods in all cleaning and sterilization work for homes, by providing the latest equipment, tools and machines that work with tremendous power and superb and amazing capabilities in cleaning
    شركة تنظيف منازل بالاحساء
    شركة تنظيف موكيت بالاحساء

    Air conditioning cleaning company in Al-Ahsa provides all the cleaning works and services for air conditioners, as it carries out complete and comprehensive cleaning of the air conditioner from the inside and outside, depending on the latest modern and advanced methods and methods.
    شركة تنظيف مكيفات بالاحساء

    There are a lot of people asking and looking for a specialized party in cleaning tanks, so we have provided you with a tank cleaning company in Al-Ahsa, tank cleaning services of all kinds.
    شركة تنظيف خزانات بالاحساء


    Al-Ahsa Insect Control Company is one of the first leading companies in the field of combating, attacking and exterminating insects, through its excellence and superiority in the control operations always everywhere and its superior ability to get rid of all kinds of insects, whether flying or crawling.شركة مكافحة حشرات بالاحساء
    شركة مكافحة الصراصير بالاحساء

    The termite control company in Al-Ahsa is interested in providing all the ingredients and capabilities necessary to combat and attack termites of all kinds, because the problem of ants is one of the problems facing many, many homes and homes.شركة مكافحة النمل الابيض بالاحساء

    A company that sprays pesticides in Al-Ahsa can combat any type of insects that haunt homes and cause anxiety, terror, tension and annoyance for the people of the house. and annihilated her on the spot.شركة رش مبيدات بالاحساء

    ReplyDelete
  19. You have quality content on your blog, I appreciate it and I'll always come around. Checkout this: Good Morning Message for Her

    ReplyDelete
  20. Hey nice blog. it's a very useful. Thank you for Sharing such type of information.

    Do you face any issue with your HP products, HP Support Assistant will help you with the configuration of your HP items in cases of difficulty.

    ReplyDelete
  21. Go to the HP Com Setup, the authority interface gave to download introduce and setup hp printer, associates with wifi with windows and mac 123 hp printer setup guide.

    ReplyDelete
  22. The best glass facade cleaning company in Riyadh relies on the latest advanced machinery and equipment that are used to clean large facades, and the cleaning and polishing process takes place in a short time, so that the place does not hang for a long time. The company provides the service of a large team of customer service personnel, who are present throughout the day in Serving the company's valued customers.
    شركة تنظيف واجهات زجاج بالرياض
    شركة تنظيف واجهات بالرياض

    ReplyDelete
  23. Hello I’m grateful to have read your content thank you. What a nice blog! I have enjoyed reading through the article although I landed on this site. If you are having issues in getting your essay writing service in australia completed accurately then do not hesitate essay typer online and get your papers checked by the best college essay writing service in AU experts at Assignment Australia.

    ReplyDelete
  24. https://www.blogger.com/comment.g?blogID=2108117660267051328&postID=3265021467088261022&page=1&token=1643287734620&isPopup=true

    ReplyDelete
  25. Thanks for sharing such a piece of informative information. You would also love to check out a love message for her

    ReplyDelete
  26. This is the best article for anyone that wants to learn about this subject. 야한동영상

    Please visit once. I leave my blog address below
    야설
    야한동영상

    ReplyDelete
  27. I delight in, cause I found just what I was looking for. You have ended my four day long hunt! God Bless you man. Have a great day. 일본야동

    Please visit once. I leave my blog address below
    한국야동
    일본야동

    ReplyDelete
  28. Great blog article. Really looking forward to read more. Will read on… 중국야동넷

    Please visit once. I leave my blog address below
    야설
    중국야동넷

    ReplyDelete
  29. afghanisthan falls under traditional legalization process. All the document has to be ratified from the concerned embassy or the counsulate.Educational certificate attestation we have two procedures Afghanistan Embassy Attestation Service , Afghanistan, is one of the major islamic country having the capital at Kabul surrounded by land multiethnic country located in the middle of south-central Asia.
    since the legalization process vary from one country to another it would be always better to complete the process from an expert hand.Indonesia Embassy Attestation Service

    ReplyDelete
  30. Thank you so much for ding the impressive job here, 토토사이트
    everyone will surely like your post. 토토

    ReplyDelete
  31. Just wish to state your own post is really amazing. The actual clarity inside your publish is actually just nice as well as we could presume you're a specialist about this topic.


    스포츠토토티비
    스포츠중계
    해외야구중계

    ReplyDelete
  32. There is no topic that is missed from their all surveying eyes in the given law topics. It makes them capable enough of writing good assignments quite easily and effectively. If you are feeling stuck with the different law topics than connect to our professional Taxation Law Assignment Help .

    ReplyDelete
  33. Hire Capstone Project Help in Malaysia from Malaysiaassignmenthelp.com to get your capstone project completed by experienced academic writers on time with error-free and plagiarism free work at nominal rates.

    ReplyDelete
  34. It was really awesome and I gain more information from your post. Thank you!
    Virginia Online Divorce

    ReplyDelete
  35. Students who are given assistance in statistics may also be led step-by-step through the process of showing statistical data in either a diagrammatic or tabular fashion. In the discipline of visual analytics, both of these methodologies are used in tandem with one another. And all of us are aware of how vitally crucial it is in the field of contemporary statistics to display data in an understandable manner. The hire online exam expert for me service allows you to complete even the most difficult data visualisation tasks in the allotted time.

    ReplyDelete
  36. A good blog always contains new and exciting information that helps readers to get useful information I am sure this is it. Now it's time to avail taxi milwaukee for more information.

    ReplyDelete
  37. Great Blog
    If you are looking for a dissertation writing service Singapore, then MyAssignmenthelp.sg is the perfect choice for you. Our Ph.D.-qualified experts to provide high-quality dissertation writing assistance to students in Singapore. We have a diverse team of dissertation writers who are well-versed in the different areas of dissertation writing such as research, proofreading, editing, and formatting. Our dissertation service in Singapore specializes in providing unique and custom-tailored dissertation help according to the guidelines and requirements provided by the students.

    ReplyDelete
  38. Hello everyone, my name is James Lord. Tute My Class is a one-stop solution for take my online class help. We offer assistance in all subjects in school and college. Whether you want us to take a math class, a nursing class, a statistics class, or an English class, our experts can handle everything for you.

    ReplyDelete
  39. Nice post
    Do you need a legal translator in Malaysia, look no further than Malaysiatranslators.com. Our skilled legal translators can help you navigate the complexities of Malaysian law and ensure that all of your legal documents are accurately translated.

    ReplyDelete
  40. https://www.blogger.com/comment.g?blogID=3053817550645181380&postID=5466263976198336716&page=1&token=1689084461875

    ReplyDelete
  41. The article on "Easy Python Decorators with the decorator decorator" simplifies the creation of Python decorators by introducing a "decorator decorator." It demonstrates practical use cases like error catch, thread safety synchronization, and object initialization manipulation. The article is a valuable resource for both beginners and experienced developers. contract dispute

    ReplyDelete
  42. Tremendous post Keep up the great work. Sharing is nice keep it up

    ReplyDelete
  43. Very nice blog post, I like this site Keep on sharing! Goodjob bud, Thanks

    ReplyDelete
  44. Nice post. Check this profile for more interesting stuffs. Awesome!

    ReplyDelete
  45. I appreciate this information. The article peaked my interest. Thanks

    ReplyDelete
  46. Canadian Freight & Shipping Companies | Get the Best LTL Freight Quotes

    Canadian Freight Quote provides shipping and logistics solutions, specializing in Less-than-Truckload (LTL) services across Canada and the USA. The company offers businesses competitive shipping rates, access to a wide network of carriers, and personalized service to meet unique shipping needs. Canadian Freight Quote aims to streamline the shipping process and reduce costs for businesses of all sizes.

    Visit Canadian Freight Quote for more information.
    https://canadianfreightquote.com/

    ReplyDelete
  47. Looking for dependable freight companies in Edmonton? Canadian Freight Quote offers comprehensive freight solutions, connecting Edmonton to Newfoundland and beyond. Whether you need to ship large commercial goods or smaller packages, we provide tailored shipping services to meet your needs. Our expert team ensures timely, cost-effective deliveries across Canada, with competitive rates and reliable service. From LTL (Less Than Truckload) to full truckload shipments, we cover all your logistics needs. Request a free quote today and experience seamless shipping solutions for your business.
    https://canadianfreightquote.com/edmonton-newfoundland/

    Operations Centre 780-970-7337
    12757 149th Street, Edmonton, AB, T5L 4M9

    ReplyDelete
  48. Excellent tutorial on Python decorators! Using the @decorator library simplifies the process, making decorators more accessible to developers of all levels. Your step-by-step examples and clear explanations demystify complex concepts. The timer and debug decorator examples demonstrate practical applications. Your code snippets are concise and easy to follow. This article remains a valuable resource even years after publication - a testament to your clear teaching style. Thanks for sharing your expertise! Want to know about virginia state police sex offender registry.

    ReplyDelete
  49. At FlexiFlex, we specialize in providing top-notch Camlock fittings in Canada for various industries. Our products are designed for durability, efficiency, and reliability, making them the go-to choice for professionals. If you’re looking for high-quality fittings that deliver outstanding performance, visit us at FlexiFlex to explore our range. We’re proud to support industries with solutions they can trust!
    Address: 8720 98 St, Fort St John, BC V1J 6B1, Canada
    Phone number: +1 250-261-6680

    ReplyDelete

Blog Archive

Google Analytics