oamer
oamer

Reputation: 103

Pythonic way to abstract common shell set up functionality

I have a multiple functions that basically trigger a shell and run some commands . They all share similar shell setup code blocks .
What is a pythonic way to abstract repetitive shell setup code in the following example ?
My proposed solution was to use a setup decorator , are there other efficient options ?

'''

def status():
    shell = setup_shell()
    with shell.run_shell():
        wait_shell_timeout(shell)
        shell.initial_setup()
        shell.get_stuff()
        shell.status()


def restore(module_name):
    shell = setup_shell()
    with shell.run_shell():
        wait_shell_timeout(shell)
        shell.initial_setup()
        shell.get_stuff()
        shell.restore(module_name)


def update(module_name):
    shell = setup_shell()
    with shell.run_shell():
        wait_shell_timeout(shell)
        shell.initial_setup()
        shell.get_stuff()
        shell.update(module_name)

'''

Upvotes: 0

Views: 42

Answers (1)

Wes Hardaker
Wes Hardaker

Reputation: 22262

There are of course many ways to pull this off. And decorators would probably be the most favorite by python advocates. And some of it depends on who you might want to use/understand the code in the long run.

Another option is callback functions:

def shell_function(routine, *args):
    shell = setup_shell()
    with shell.run_shell():
        wait_shell_timeout(shell)
        shell.initial_setup()
        shell.get_stuff()
        routine(shell, *args)

shell_function(Shell.status)
shell_function(Shell.restore, module_name)

This can be a bit easier to understand what's going on for newbies that don't understand decorators well, but works kinda similarly under the hood.

In the end: know your target audience.

Upvotes: 2

Related Questions