-1

Some external code runs my function of the following code:

def __init__(self,weights=None,threshold=None):

    print "weights: ", weights
    print "threshold: ", threshold

    if weights:
        print "weights assigned"
        self.weights = weights
    if threshold:
        print "threshold assigned"
        self.threshold = threshold

And this code outputs:

weights:  [1, 2]
threshold:  0
weights assigned

I.e. print operator behaves like threshold is zero, while if operator behaves like it was not defined.

What is the correct interpretation? What is happening? What is the state of threshold parameter and how to recognize it?

ymyzk
  • 923
  • 7
  • 12
Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

6

Use if weights is not None instead of if weights.

More detail: when you say if weights you're asking Python to evaluate weights in a boolean context, and many things can be "false-equivalent" (or "falsy") including 0, empty strings, empty containers, etc. If you want to only check for a None value, you have to do that explicitly.

tzaman
  • 46,925
  • 11
  • 90
  • 115
0

You can explicitly test for a None value.

def __init__(self,weights=None,threshold=None):
    print "weights: ", weights
    print "threshold: ", threshold

    if weights is not None:
        print "weights assigned"
        self.weights = weights
    if threshold is not None:
        print "threshold assigned"
        self.threshold = threshold
Martin Hallén
  • 1,492
  • 1
  • 12
  • 27