python: mutating `globals` to dynamically put things in scope

僤鯓⒐⒋嵵緔 提交于 2019-12-04 14:58:23

I think continuously duckpunching globals is definitely a terrible idea. Relying on globals seems like the antithesis of the functional style you're emulating here.

Why not define m_chain as:

def m_chain(bind, *fns):
    """returns a function of one argument which performs the monadic
    composition of fns"""
    def m_chain_link(chain_expr, step):
        return lambda v: bind(chain_expr(v), step)
    return reduce(m_chain_link, fns, unit)

Then:

identity_m = {
    'bind':lambda v,f:f(v),
    'unit':lambda v:v
}

with monad(identity_m):
    assert m_chain(lambda x:2*x, lambda x:2*x)(2) == 8

Becomes simply:

assert m_chain(lambda v,f:f(v), lambda x:2*x, lambda x:2*x)(2) == 8

Actually passing the function explicitly seems more pythonic and doesn't seem to cause you to lose any flexibility.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!