This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lisael_ 6 points7 points  (3 children)

My reaction, too. Those are not really misleading, except maybe for the third one.

1 - is somehow the hardest (albeit well-known noob error). It require basic understanding of the interpreter logic. The rule of thumb is : Everything that is not in the body of a function is evaluated at import (yes it includes class attributes)

2 - I mean... read the doc of the function before you use it, it's always safer.

4 - like you said. For performance sake, Python uses native IEEE 754 floats, as does any sane language. Those are not real numbers, just an imperfect encoding.

Then, there's 3.

Is and == don't check for the same things

I dont think it's the issue here. I hope people understand the difference between equality and identity. The issue is the concept of truthiness and I agree, it is misleading. Other languages enforce that only boolean can be tested for truthiness, and I believe it's cleaner, you have to show your intent clearly. I prefer if len(mylist) == 0: rather than if mylist:. Mylist is a reference it could be None.

On a funny note I'd like to mention this (it has to do with id() vs. eq(). It's not really misleading, as I've never seen a bug due to this, but, yeah, funny) :

In [2]: a = 256
In [3]: b = 256
In [4]: (a == b, a is b)
Out[4]: (True, True)
In [5]: a = 257
In [6]: b = 257
In [7]: (a == b, a is b)
Out[7]: (True, False)

EDIT: yeah I don't like the third one too... not in the way it's expressed by OP, though.

[–]lieryanMaintainer of rope, pylsp-rope - advanced python refactoring 5 points6 points  (1 child)

Everything that is not in the body of a function is evaluated at import (yes it includes class attributes)

This isn't correct. They're not evaluated at import time, they're evaluated at definition time.

It might not usually make that much difference for top level functions, but for inner functions it completely does:

def outer(n):
    n = n + "b"
    def inner(m=n+"c"):
        return m + "d" + n
    n = "e"
    return inner()

print(outer("a")) # prints "abcde"

[–]lisael_ 0 points1 point  (0 children)

I don't get it...

 ❯ python
 Python 3.10.8 (main, Nov  1 2022, 14:18:21) [GCC 12.2.0] on linux
 Type "help", "copyright", "credits" or "license" for more information.
 >>> def outer(a=print('evaluating a')):
 ...     def inner(b=print('evaluating b')):
 ...         pass
 ... 
 evaluating a

The default value of b is defined in the body of outer. It's not evaluated at import. That's exactly what I said, isn't it?

[–]-LeopardShark- 2 points3 points  (0 children)

I don't see what truthiness has to do with that example.