Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

Check that Python function does not modify argument?

You know how in Python, if v is a list or a dictionary, it's quite common to write functions that modify v in place (instead of just returning the new value). I'm wondering if it is possible to write a checker that identifies such functions.

For simplicity, say you have a function f, which only takes one argument - a and returns in finite time (the return value is actually irrelevant). Assume also that for any input value v, f(v) always does the same thing (i.e. the logic inside of f does not depend on any context or environment values - it's a pure computation on a).

Is it possible to write a function m, such that m(f, v) returns True if and only if f(v) actually changes the original value of v?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No; this is equivalent to the Halting problem. If such an m did exist, then I could just write:

def f(a):
    if m(f, a):
        return a
    else:
        # Modify `a` somehow
        return a

and we get a contradiction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...