Search code examples
pythondecoratorqsub

Is it possible to make a context-dependent function?


I have used the following script to run the script directly and just to make a bash command line for running it outside the script (e.g. job scheduler).

def qsubcommand(func):
    def wrapper(*args, **kwargs):
        if kwargs.get('test', False):
            cmdl = ' '.join(['this.py', func.__name__, *map(str, args)])
            return cmdl
        else:
            return func(*args, **kwargs)
    return wrapper

@qsubcommand
def calculate(value1, value2):
   # do something

if __name__ == '__main__':
    if len(sys.argv) > 1:
        func, args = sys.argv[1], sys.argv[2:]
        if func in locals().keys():
            locals()[func](*args)
        else:
            raise NotImplementedError

I have a lot of functions like 'calculate'. I'm working with the script for running and testing a program.

# When I want to run directly:
>>> calculate(4, 5)

# When I want to just print command line:
>>> calculate(4, 5, test=True)
'this.py calculate 4 5'

However, I want to use it in a context-dependent manner like below.

# When I want to run directly:
>>> test = False
>>> calculate(4, 5)

# When I want to just print command line:
>>> test = True
>>> calculate(4, 5)
'this.py calculate 4 5'

How can I modify to let the function recognize the variable outside the scope. Is it possible to access a variable outside the function?

Thank you for your kind answers in advance.


Solution

  • Just put this on the part of the function where you want to check the variable:

    if 'test' in globals() and test:
        # do test
    else:
        # do normal
    

    Functions can always access variables which are outside the function scope, they just can't edit them if you don't use the global keyword.