vendredi 7 juillet 2017

Strange behavior of python trenary if operator

I has writing a simple heap class, not that is relevant. In the init function of the class i write the following piece of code

def __init__(self, fn=None):
    self.heap = ["start"]  
    self.size_ = 0
    # condition of heap for no change to happen. default is min heap
    self.fn = lambda parent_, child_: (parent_ < child_) if fn is None else fn

When i use the self.fn function (when i pass an argument and not None) it will not work. For example when I say

maxHeap = BinaryQueue(fn=lambda x, y: x > y)
print(maxHeap.fn(3, 4))

It will output <function <lambda> at 0x00000135EB76D1E0>

if i write

def __init__(self, fn=None):
    self.heap = ["start"] 
    self.size_ = 0
    # condition of heap for no change to happen. default is min heap
    if fn is None:
        self.fn = lambda parent_, child_: parent_ < child_
    else:
        self.fn = fn

it will correctly output False since 3>4 is False

Any ideas why the trenary version is not working? (using python 3.6)

Aucun commentaire:

Enregistrer un commentaire