1

I'm writing a feature generation class that can be extendable. For example in the following example any method that starts with generate is a feature generation method:

class FeatureGenerator:
    def __init__(self): 
        self.generate_a()
        self.generate_b()
    def method_a(self): pass
    def generate_a(self): do stuffs
    def generate_b(self): do stuffs

I want to execute all methods with generate prefix within init. However, I don't want to add it manually every time I write a new method. One solution could be writing a decorator that will add it to a list and then execute all elements in the list within init. But I am not sure that's a good idea. Is there any pythonic way to do that?

1 Answer 1

2

Using the dir of the instance:

class FeatureGenerator:
    def __init__(self): 
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and name.startswith("generate"):
                attr()
    def method_a(self): pass
    def generate_a(self): print("gen a")
    def generate_b(self): print("gen b")
Sign up to request clarification or add additional context in comments.

5 Comments

I would manually walk through the MRO.. dir is not meant to be used this way. The docs evens state "supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names". So just for klass in type(self).mro(): for attr, name in vars(klass).items():...
maybe even skip object: for klass in type(self).mro()[:-1]
You probably meant for name, attr in vars(...)
Thanks! I experimented with both the answer and both works well for my purpose. To make juanpa.arivillaga's answer complete: for klass in type(self).mro()[:-1]: for name, attr in vars(klass).items(): if name.startswith('generate'): attr(self)
^ Beware that using vars would require special handling for classmethod and staticmethod (dir does not)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.