tags:

views:

99

answers:

4

Hi,

Today, i lost a lot of time fixing a stupid error in my code. Very simplified, the problem was this:

def f():
    return 2

2 == f

I forgot to write the parenthesis in the sentence, so I compared a pointer function with a number.

Ok, my question:

Is there any way to change the interpreter to be more stricted with the code? Show more warnings for example...

Thanks ^^

+3  A: 

The interpreter shouldn't issue a warning. f could be reassigned to an integer and then the check would totally makes sense:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     return 2
... 
>>> 2 == f
False
>>> f = 2
>>> 2 == f
True
Peter Jaric
I am not saying it would be good practice though.
Peter Jaric
+5  A: 

Python is a dynamic language, and the construct you have shown is completely valid (a function is not equal to 2). There is no strict mode.

Yann Ramin
+3  A: 

One of the disadvantages of working with a dynamically typed language is that the language environment has very little or no information about the types of things when it sees a statement, so it can issue no warning when it sees it, only when the statement is executed.

For various reasons it's very convenient for all types to be able to be compared to all others for equality. It makes heterogeneous containers much easier to write. So comparing a function to an integer is a defined thing to do, and since that can happen in so many useful cases, the interpreter can't really give you a warning about it at runtime. And while the construct is questionable, it can't give you a warning when it sees the statement (as opposed to executing it) because then it doesn't have the necessary type information to issue the warning.

Omnifarious
+1  A: 

You are comparing a function to an integer, which is perfectly valid. In this case the condition will just always be False as it will compare the object identities. In Python, functions never know what types they are getting, and will just compare them blindly, this allows for polymorphic behaviour. There is no way to disable this, besides switching to a statically typed language.

Longpoke