Ad

Can I Use Decorator Under The Terms?

- 1 answer

I have my own python library. And I use the decorator @send_transport from it.

@send_transport(program_version=__version__, entity=1)
def post(self):
    pass

Can I implement something like this?

try:
    from spo_client import send_transport    
except ImportError:
    pass
else:
    @send_transport(program_version=__version__, entity=1)
def post(self):
    pass
Ad

Answer

In order to achieve your goal, you can do

try:
    from spo_client import send_transport    
    decorator = send_transport(program_version=__version__, entity=1)
except ImportError:
    decorator = lambda f: f

@decorator
def post(self):
    pass

This creates either the "correct" decorator or a dummy on which will transform the function into itself, i. e. leave it alone.

Another option could be to define a dummy send_transport function:

def dummy_send_transport(*a, **k):
    return lambda f: f

try:
    from spo_client import send_transport    
except ImportError:
    send_transport = dummy_send_transport
    # or just send_transport = lambda *a, **k: lambda f: f
    # but then the code would be less self-documenting.

@send_transport(program_version=__version__, entity=1)
def post(self):
    pass

In this case, on an import error, the send_transport() is substituted by a version which just returns a NOP decorator, but which can be called as its "original". Here, you can have several different send_transport calls in your code and don't have to predefine a variable for them.

Ad
source: stackoverflow.com
Ad