pacopepe222
pacopepe222

Reputation: 191

Interpreter more strict

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 ^^

Upvotes: 1

Views: 216

Answers (4)

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.

Upvotes: 1

Omnifarious
Omnifarious

Reputation: 56038

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.

Upvotes: 3

Yann Ramin
Yann Ramin

Reputation: 33177

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.

Upvotes: 5

Peter Jaric
Peter Jaric

Reputation: 5302

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

Upvotes: 3

Related Questions