Code Monkey home page Code Monkey logo

Comments (6)

micheles avatar micheles commented on July 24, 2024

from decorator.

neimad1985 avatar neimad1985 commented on July 24, 2024

Hi, thanks for the quick reply !
I am not sure I understood your answer correctly. Or maybe it did not explain well enough what I want to achieve. With this optional argument I want to able to either use the decorator as @printer or @printer("some string").

I adapted my code following your remark (I also renamed the inner _printer function to inner_printer for clarity's sake):

import decorator

def _printer(text=None):
    def _inner_printer(func, *args, **kwargs):
        if text:
            print(text)
        func(*args, **kwargs)
    return decorator.decorator(_inner_printer)
printer=_printer()

@printer
def world():
    print("World")

@printer("Goodbye")
def universe():
    print("Universe")

The thing is that the function world gets decorated correctly but universe breaks the interpreter at definition time with the following error.

Traceback (most recent call last):
  File "toto.py", line 15, in <module>
    @printer("Goodbye")
  File "<decorator-gen-1>", line 2, in _inner_printer
  File ".../lib64/python3.4/site-packages/decorator.py", line 240, in decorate
    evaldict, __wrapped__=func)
  File ".../lib64/python3.4/site-packages/decorator.py", line 215, in create
    name, rest = obj.strip().split('(', 1)
ValueError: need more than 1 value to unpack

Did I misunderstood your solution ? Could you correct my code ?

from decorator.

linar-jether avatar linar-jether commented on July 24, 2024

Stumbled on using optional decorator arguments, and found no docs on this.., came up with this solution:

*Note that this works for optional arguments, but limits you to use kwargs only.

import decorator

def printer(_func=None, text='blah'):

    def _printer(func, *args, **kwargs):
        if text:
            print(text)
        func(*args, **kwargs)

    if _func:
        return decorator.decorate(_func, _printer)

    return decorator.decorator(_printer)

@printer
def world():
    print("World")

@printer(text='Hello')
def hello():
    print("World")

world()
hello()

I suggest adding a section on optional arguments to the docs.

from decorator.

micheles avatar micheles commented on July 24, 2024

This is a creative solution that works. Still, I do not like the whole idea, too much magic. What's wrong with having two parenthesis at the end of the decorator? Using printer() to me looks a lot clearer.

from decorator.

neimad1985 avatar neimad1985 commented on July 24, 2024

I agree with the "not too much magic" statement. I will use empty parenthesis though but thanks for the proposal.
I just asked this question in the first place in case i had missed something about how to use decorators. It finally seems that this is not a lack of knowledge but just some kind of edge case. Thanks for your time guys. For me, the ticket can be closed.

from decorator.

micheles avatar micheles commented on July 24, 2024

@neimad1985 since PEP 557 has been accepted (https://www.python.org/dev/peps/pep-0557) I have given up. If Guido thinks that it is fine to drop the parenthesis in a decorator factory, then it is fine. Starting from today (release 4.2.0) the following code is valid and does what you want:

@decorator.decorator
def printer(func, text='hello', *args, **kwargs):
    print(text)
    return func(*args, **kwargs)

@printer
def world():
    print("World")

from decorator.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.