Condional annotations on a class in python
<p>Below is the code snippet I want to accomplish. Please help!</p>

<pre><code>try:
    from cinder import interface
    interface_available = True
except ImportError:
    interface_available = False

@interface.volumedriver
class EMCCoprHDFCDriver(driver.FibreChannelDriver):
</code></pre>

<p>Now the above would give an error in case the 'interface' module is not available, i.e, interface_available = False.
However, if the 'interface' module is available, the annotation should be used above the class.</p>

<p>Is there any way, I can do this? Thanks. </p>

<p>Yes there is. </p>

<p>If the decorator does not exist then simply use the identity decorator to perform a no-op:</p>

<pre><code>try:
    from cinder.interface import volumedriver
except ImportError:
    def volumedriver(func):
        return func

@volumedriver
class EMCCoprHDFCDriver(driver.FibreChannelDriver):
</code></pre>

<hr>

<p>Why this works:</p>

<p>A python decorator:</p>

<pre><code>@decorator
def some_function:
    pass
</code></pre>

<p>is just syntactic sugar for calling:</p>

<pre><code>some_function = decorator(some_function)
</code></pre>

<p>If we think about decorators this way, it is clear that if we want to apply a decorator that does nothing (the no-op decorator or identity decorator) we should make a decorator that returns the original function. </p>

<pre><code>def identity(func):
    return func

@identity
def func():
    pass
</code></pre>

python class conditional python-decorators