zincware / supercharge

Expand Python Super Capabilities

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Build tests passing Project license Code style: black Code coverage Open Example in Google Colab

Supercharge

This package allows you to automatically run code before and after a given class method. Furthermore, this behaviour can be enforced on child classes as well.

Supercharge is available via:

pip install supercharge

Example

from supercharge import Charge

class HelloWorld:
    def __init__(self):
        self.run_prepared = False
        self.run_state = False

    @Charge
    def run(self):
        if self.run_prepared:
            print("running ...")

    @run.enter
    def pre_run(self):
        self.run_prepared = True

    @run.exit
    def post_run(self):
        self.run_state = True

If this is behaviour is desired in subclassed runs one must use the Base class.

from supercharge import Charge, Base

class HelloWorld(Base):
    def __init__(self):
        self.run_prepared = False
        self.run_state = False

    @Charge
    def run(self):
        raise NotImplementedError

    @run.enter
    def pre_run(self):
        self.run_prepared = True

    @run.exit
    def post_run(self):
        self.run_state = True

class Child(HelloWorld):
    def run(self):
        if self.run_prepared:
            print("running ...")

Noticeable Alternatives

Using supercharge might not always be the best way to go. In many scenarios an easier way to achieve a similar functionality can be

class HelloWorld:
    def __init__(self):
        self.run_prepared = False
        self.run_state = False

    def run(self):
        self.pre_run()
        self.base_run()
        self.post_run()

    def base_run(self):
        raise NotImplementedError

    def pre_run(self):
        self.run_prepared = True

    def post_run(self):
        self.run_state = True

class Child(HelloWorld):
    def base_run(self):
        if self.run_prepared:
            print("running ...")

where you call Child.run() and overwrite Child.base_run().

About

Expand Python Super Capabilities

License:Eclipse Public License 2.0


Languages

Language:Python 100.0%