0

This is an extension of Dynamic/runtime method creation (code generation) in Python

@John Montgommery properly answered @Eli Bendersky 's question that you can dynamically create a class with function using this logic:

class Dynamo(object):
    pass

def add_dynamo(cls,i):
    def innerdynamo(self):
        print "in dynamo %d" % i
    innerdynamo.__doc__ = "docstring for dynamo%d" % i
    innerdynamo.__name__ = "dynamo%d" % i
    setattr(cls,innerdynamo.__name__,innerdynamo)

for i in range(2):
    add_dynamo(Dynamo, i)

d=Dynamo()
d.dynamo0()
d.dynamo1()

My question is: How do you decorate the resulting functions within that class with a decorator that needs a parameter?

eg: Static function definition:

class MyTaskSequence(TaskSequence):
    @seq_task(1)
    def sequence1(self):
        self.client.get("/devops/")

    @seq_task(2)
    def sequence2(self):
        self.client.get("/blog/")

What I tried:

class MyTaskSequence(TaskSequence):
    pass


def add_sequence(cls, order, path):
    def sequence(self):
        self.client.get(path)
    sequence.__name__ = "sequence%d" % order
    setattr(cls, sequence.__name__, seq_task(order)(sequence))

add_sequence(MyTaskSequence, 1, "/devops/")
add_sequence(MyTaskSequence, 2, "/blog/")
Marius Mitrofan
  • 125
  • 1
  • 6

1 Answers1

0

You can directly apply the decorator when creating the method:

def add_sequence(cls, order, path):
    @seq_task(order)
    def sequence(self):
        self.client.get(path)
    sequence.__name__ = "sequence%d" % order
    setattr(cls, sequence.__name__, sequence)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • Thank you. It worked. I've printed the "order" value within that decorator function and it properly "fetched" the value. – Marius Mitrofan Oct 05 '19 at 08:13
  • Do you happen to also know the answer to a follow-up of this -> https://stackoverflow.com/questions/58247910/ensure-that-a-function-created-dynamically-inside-a-class-can-also-be-used-as-a ? – Marius Mitrofan Oct 05 '19 at 11:32