V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
billgreen1
V2EX  ›  Python

请教如何避免函数的副作用

  •  
  •   billgreen1 · May 23, 2018 · 4634 views
    This topic created in 2910 days ago, the information mentioned may be changed or developed.

    我现在有许多函数,都是这样定义的:

    def func1(context):
        context_ = copy(context)
        # do something
        context_.xxx = xxxx
        return context_
    

    因为我不想因为副作用修改传入的参数,所以函数的首行,都 copy 了一下。 觉得这样有些重复,有没有什么方法,比如装饰器,或者 context manager,省去每次显式 copy 的做法?

    ps: 我是有许多这样的函数,想创建一个 pipeline,为了简单就入参和出参一样了

    16 replies    2018-06-07 18:06:49 +08:00
    tempdban
        1
    tempdban  
       May 23, 2018 via Android
    不清楚 copy 是否有用,但是 copy.deepcopy 一定不会错。
    装饰器搞得定。
    iwishing
        2
    iwishing  
       May 23, 2018
    在调用前复制一下入参不行么?所有的函数调用都不想改入参?需要改入参的情况才是常态吧?
    chaleaochexist
        3
    chaleaochexist  
       May 23, 2018
    装饰器的典型应用场景...
    面向切面了解一下.
    lieh222
        4
    lieh222  
       May 23, 2018
    避免函数的副作用的正确方法就是不写函数,不写函数就不用传参,不传参就不用担心副作用,不写函数就不用调用,像写作文一样去写
    loongwang
        5
    loongwang  
       May 23, 2018
    @lieh222 那还怎么维护
    lieh222
        6
    lieh222  
       May 23, 2018
    @loongwang 维护不是别人的事吗,写完你就该撤了
    clino
        7
    clino  
       May 23, 2018
    为什么不写类来表达上下文?
    一个对象内部的数据就可以作为上下文
    clino
        8
    clino  
       May 23, 2018
    哦,楼主的重点是每次要复制一份新的上下文来用哈
    lolizeppelin
        9
    lolizeppelin  
       May 23, 2018
    写一个专门的复制函数复制你的 context

    用装饰器加复制函数实现预复制功能
    loongwang
        10
    loongwang  
       May 23, 2018   ❤️ 1
    @lieh222 !!! 这种思想能写好程序?对自己的代码负责,ok ?
    jmc891205
        11
    jmc891205  
       May 23, 2018
    每个函数开头都 copy 一下?浪费了 memory 又拖慢了 performance
    enenaaa
        12
    enenaaa  
       May 23, 2018
    封装好 context, 只给特定的代码修改权限呗
    lululau
        13
    lululau  
       May 23, 2018 via iPhone
    因噎废食,熟练掌握语言,知道哪些操作会修改对象哪些不对,在纯函数里不在参数上调用那些会修改对象的函数 /方法就可以了
    quinoa42
        14
    quinoa42  
       May 24, 2018
    我觉得你需要的是实现 immutable object,而不是手动 copy
    omg21
        15
    omg21  
       May 25, 2018
    @lieh222 不要故意带歪路。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3405 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 12:16 · PVG 20:16 · LAX 05:16 · JFK 08:16
    ♥ Do have faith in what you're doing.