简体   繁体   中英

Seek python warning for a multiply defined function

Q: is there a way to get Python to give me a warning when there is more than one definition of the same function, conflicting, etc.

(I just wasted a bit of time making edits to two different versions of the same function.)

A small example of conflicting function definitions:

$>  cat ./foo2.py
cat ./foo2.py
def foo():
    print "1st definition of foo()"
def foo():
    print "2nd definition of foo()"
foo()

Executing - Python uses the last definition. (By the way, is that officially defined? It is useful semantics, eg when creating functions on the fly in strings and evaling them. It is useful in an interpreter. But it masks bugs in some circumstances, hence my desire to have an optional warning.)

$>  python ./foo2.py
python ./foo2.py
2nd definition of foo()

"python -W all" doesn't give a warning:

$>  python -W all ./foo2.py
python -W all ./foo2.py
2nd definition of foo()

Neither does "use warnings".

For that matter, python3 does the same as the above (although python3 requires parens around the argument to print :-( ).

pylint DOES report the error

E:  4, 0: function already defined line 2 (function-redefined)

but I have the usual objections to separate lint tools that should be well-known to anyone familiar with the history of programming languages. (Eg lint is noisy; lint is optional, not always run; lint is optional, eg was not installed automatically with python, and required me to do some hacks to get to install (homebrew problems?) - I almost gave up, and if I had given up I would not have had pylint.)

Therefore, even though pylint does find the error, I still ask:

Q: is there any way to get python itself to report an error or warning for multiply defined functions?

===

By comparison, and in response to folks who say "Why would you want to do that in a dynamic language?"

Perl is also a dynamic language. When Perl first came out, it did not have such warnings. But now it does, as people realized that such warnings are good for code quality.

Perl does not warn about multiple definitions by default, but does warn with -Wall or use warning.

$>  cat foo2.pl
cat foo2.pl
sub foo { print "foo#1" }
sub foo { print "foo#2" }
foo()

$>  perl -Wall ./foo2.pl
perl -Wall ./foo2.pl
Subroutine foo redefined at ./foo2.pl line 2.
foo

No, there's no way to get Python to behave this way natively. A function definition is essentially an assignment to a name, and names in Python can be reassigned at any time. Functions are not treated in any special way compared to integers, strings, etc.

您可以修饰所有功能,并创建符号数据库并警告重新定义。

语言没有内置任何东西,但是您可以使用诸如pylint之类的代码检查工具(并且我相信还有其他工具),该工具会发现这类情况并就此警告您。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM