Proper use of decorators

I just started using decorators in Python, and I'm not sure how to use it properly.

Let's say I have this code:

def viable_decorator(fonction_viable):
    def viable(sequences, pos):
        codons = [seq[pos:pos+3] for seq in sequences]
        return not any("-" in codon for codon in codons)
    return viable

@viable_decorator
def viable(sequences, pos):
    codons = [seq[pos:pos+3] for seq in sequences]
    return not all("-" in codon for codon in codons)

sequncess = ["---aaacacaacaacaaat",
             "------aaacacacac---",
             "aaggcggaggcgg---ggg",]

print viable(sequences, 0)

My goal is to use an alternative two versions of the function viable(), depending on the situation. Is this how decorators work? And if so, how to determine the choice of function viable()? Because for now, in this code, the decorator is always called.

Thanks in advance.

+4
source share
3 answers

This is how decorators should work?

No. Typically, decorators should “decorate” the original function or add some additional material to the original. Do not create new, not related to decorated.

In your particular case:

def viable_decorator(fonction_viable):
    def viable(sequences, pos):
        codons = [seq[pos:pos+3] for seq in sequences]
        return not any("-" in codon for codon in codons)
    return viable

fonction_viable. , , , , .

+4

Python3 functools.wraps viable:

import functools
def viable_decorator(fonction_viable):
  @functools.wraps(fonction_viable)
  def viable(sequences, pos):
    codons = [seq[pos:pos+3] for seq in sequences]
    return not any("-" in codon for codon in codons)
  return viable

@viable_decorator
def viable(sequences, pos):
   codons = [seq[pos:pos+3] for seq in sequences]
   return not all("-" in codon for codon in codons)

unwrapped_viable = viable.__wrapped__

viable viable_decorator. unwrapped_viable viable viable_decorator.

+1

, , . "fonction_viable", .

, - , .

+1

Source: https://habr.com/ru/post/1694095/


All Articles