【问题标题】:Is it possible to make a context-dependent function?是否可以制作依赖于上下文的功能?
【发布时间】:2018-09-07 10:59:49
【问题描述】:

我使用以下脚本直接运行脚本,只是为了制作一个 bash 命令行以便在脚本之外运行它(例如作业调度程序)。

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

我有很多函数,比如“计算”。 我正在使用脚本来运行和测试程序。

# 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'

但是,我想以与上下文相关的方式使用它,如下所示。

# 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'

如何修改以让函数识别范围之外的变量。 是否可以访问函数外的变量?

提前感谢您的友好回答。

【问题讨论】:

    标签: python decorator qsub


    【解决方案1】:

    只需将其放在要检查变量的函数部分:

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

    函数总是可以访问函数范围之外的变量,如果你不使用 global 关键字,它们就无法编辑。

    【讨论】:

    • 我想知道我是否也可以通过将它添加到装饰器函数'qsubcommand()'而不是'calculate()'之类的函数来使用你的答案。
    • @SukjunKim 我不明白你为什么不能,自己试试吧:)
    • 感谢您的评论。为了使其更通用,如何在调用函数的本地范围内使用它?我应该使用inspect 模块吗?
    • @SukjunKim 我不太明白你的意思。附言如果您认为我的回答回答了您的问题,请随时将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2021-10-11
    相关资源
    最近更新 更多