1

我的直觉知道这很糟糕,我只是无法确切说明原因。

variable = globals()['__builtins__'][sys.argv[1]]

对于我的项目,我将实现一个字典,该字典将从命令行获取我需要的类名,因此我可以限制和控制有效输入。但我最初是这样写的,然后就像等待,这很糟糕。我只是无法说出确切的原因。

有人知道一篇文章或以前回答的问题可能会解决这个问题吗?

4

1 回答 1

3

If you're going to do input sanitization anyway, it could also be written as:

ALLOWED_ARGS = {"repr", "str", "unicode"}
funcs = {f: getattr(__builtins__, f) for f in ALLOWED_ARGS}
# funcs.update({"custom": custom_func})

# I'd also assert on all functions having the same arity,
# but this is tricky with builtins...

func = funcs[sys.argv[1]]

Not sure why, but seems somehow safer to me.

If you're positive, input is always correct, your code seems fine to me, except that __builtins__[name] shouldn't work and you have to use getattr(__builtins__, name).

于 2013-05-10T21:03:24.203 回答