Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid if __name__ == '__main__' in Python subclasses to be run using function from parent

I have a generic class (A) which is to be subclassed a lot like this:

class A:
    def run(self):
        ...
        self.do_something()
        ...

    #abstract function
    def do_something(self):
        pass


class B(A):
    def do_something(self):
        ...

The subclasses are in separate files that I'm running directly by adding this code to each file (B is the name of the subclass in the file):

if __name__ == '__main__':
    B().run()

My question is, can I avoid having to add this code to all files with the subclasses since the only thing that changes in the code is the class being used (B in the example)?

like image 657
Francisco Vieira Avatar asked Sep 12 '11 11:09

Francisco Vieira


People also ask

How do you avoid inheritance in Python?

The way to "avoid" inheritance here would be to rename _private_var and make it a class-private name. i.e. __private_var . If you do this, running your code will cause an AttributeError: 'Child' object has no attribute '_Parent__private_var' (note the _Parent prefix automatically added).

What is name __ main __ in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

What is __ main __ class?

__main__ is the name of the module, here as you are directly executing it, its being considered as a script and all scripts have the name __main__ in Python. There's a . in between because Fraction is an attribute of the script __main__ , the module; and belongs to the module level scope.

How do you create a subclass in Python?

The process of creating a subclass of a class is called inheritance. All the attributes and methods of superclass are inherited by its subclass also. This means that an object of a subclass can access all the attributes and methods of the superclass.


1 Answers

If your python version is recent enough, you can create a class decorator.

In this case, an indirect one.

def runifmain(mainname):
    def deco(clas):
        if mainname == '__main__':
            clas().run()
        return clas
    return deco


@runifmain(__name__)
class B(A):
    [...]

should do the job if you define runifmain() somewhere centrally and just use the @runifmain(__name__)wherever it is needed.

like image 50
glglgl Avatar answered Sep 28 '22 08:09

glglgl