python - 是否可以更改当地人的命令?

原文 标签 python python-3.x dispatch

Is it possible to change the locals dict?

Basically instead of this:

context1.a
context1.b()
context2.a
context2.b()

I want to write:

with context1():
    a
    b()

with context2():
    a
    b()

Ideally I would do this by switching out the "locals dictionary" with an object with a custom __get__, but I'm not aware of how to do that or if it's even possible.

Why?: I've implemented a kind of predicate dispatching (for fun), but I can only use by explicitly naming the context each time: context.a() + context.b() is annoying to write all the time.

Answer

Don't do that. Just because a Turing machine can do something doesn't mean that's a good way to communicate your intent to folks.

Simply stick to standard syntax, and then your code will be clear to other engineers.

    with context1() as c:
        c.a
        c.b()

翻译

基本上代替这个:

context1.a
context1.b()
context2.a
context2.b()


我想写:

with context1():
    a
    b()

with context2():
    a
    b()


理想情况下,我将通过使用带有自定义__get__的对象切换“本地字典”来实现此目的,但是我不知道该怎么做或什至可能。

为什么?:我实现了一种谓词调度(出于娱乐目的),但是每次只能通过显式命名上下文来使用:context.a() + context.b()总是很烦人。
最佳答案
不要那样做仅仅因为图灵机可以做某事并不意味着这是向人们传达您的意图的好方法。

只需坚持使用标准语法,其他工程师就可以清楚地看到您的代码。

    with context1() as c:
        c.a
        c.b()
相关推荐

python - 为Python2和Python3编写Unicode正则表达式

python - pip安装tesserocr失败,并显示错误“ tesserocr的建筑轮失败”

python - webbrowser python在同一选项卡中打开新的URL。这行得通吗?

python - 使用Python进行轨迹聚类/聚合

python - 使用model.fit_generator时keras val非常慢

python - 在Python 2.7中模拟布尔__bool__协议方法

python - 为什么“ nparray.tolist()”占用了这么多空间?

python - 减少(倍数)熊猫

python - 具有不同形状的Tensorflow元组

python - 在Spark中广播用户定义的类