Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python allow comparison of a callable and a number?

Tags:

python

I used python to write an assignment last week, here is a code snippet

def departTime():
    '''
    Calculate the time to depart a packet.
    '''
    if(random.random < 0.8):
        t = random.expovariate(1.0 / 2.5)
    else:
        t = random.expovariate(1.0 / 10.5)
    return t

Can you see the problem? I compare random.random with 0.8, which should be random.random().

Of course this because of my careless, but I don't get it. In my opinion, this kind of comparison should invoke a least a warning in any programming language.

So why does python just ignore it and return False?

like image 236
ablmf Avatar asked Mar 16 '26 12:03

ablmf


2 Answers

This isn't always a mistake

Firstly, just to make things clear, this isn't always a mistake.

In this particular case, it's pretty clear the comparison is an error.

However, because of the dynamic nature of Python, consider the following (perfectly valid, if terrible) code:

import random
random.random = 9 # Very weird but legal assignment.
random.random < 10 # True
random.random > 10 # False

What actually happens when comparing objects?

As for your actual case, comparing a function object to a number, have a look at Python documentation: Python Documentation: Expressions. Check out section 5.9, titled "Comparisons", which states:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a cmp method or rich comparison methods like gt, described in section Special method names.

(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)

That should explain both what happens and the reasoning for it.

BTW, I'm not sure what happens in newer versions of Python.

Edit: If you're wondering, Debilski's answer gives info about Python 3.

like image 108
Edan Maor Avatar answered Mar 19 '26 02:03

Edan Maor


This is ‘fixed’ in Python 3 http://docs.python.org/3.1/whatsnew/3.0.html#ordering-comparisons.

like image 44
Debilski Avatar answered Mar 19 '26 01:03

Debilski