cosmologicon / pywat

Python wats
1.22k stars 99 forks source link

Other wats suggestions #19

Open Lucas-C opened 8 years ago

Lucas-C commented 8 years ago

First: thanks for this list, and the amazingly difficult AND fun quiz !

Now, a few suggestions to add to your collection of gotchas:

[] = () # OK
() = [] # KO

bool(datetime.time()) is False # cf. "a false midnight" http://lwn.net/Articles/590299/

x = 256
y = 256
assert (x is y) is True
x = 257
y = 257
assert (x is y) is False
x = 257; y = 257
assert (x is y) is True
# cf. http://stackoverflow.com/q/306313/636849

i=0;a=[0,0]
i, a[i] = 1, 10
print i, a  # 1, [0,10] - cf. https://news.ycombinator.com/item?id=8091943 - Original blog post from http://jw2013.github.io

def create_multipliers(n):
    return [lambda x : i * x for i in range(1,n+1)]
for multiplier in create_multipliers(2):
    print multiplier(3) # Late Binding Closure : prints 6 twice

issubclass(list, object) # True
issubclass(object, collections.Hashable) # True
issubclass(list, collections.Hashable) # False - There are 1449 such triplets (4.3% of all eligible triplets) in Python 2.7.3 std lib

And I found out about those last 3 myself:

d = {'a':42}
print type(d.keys()[0]) # str
class A(str): pass
a = A('a')
d[a] = 42
print d # {'a':42}
print type(d.keys()[0]) # str

f = 100 * -0.016462635 / -0.5487545  # observed on the field, in a real-world situation
print 'float     f:', f              # 3.0
print 'int       f:', int(f)         # 2

class O(object): pass
O() == O()             # False
O() is O()             # False
hash(O()) == hash(O()) # True !
id(O()) == id(O())     # True !!!
# ANSWER: http://stackoverflow.com/a/3877275/636849
mpanczyk commented 8 years ago

f = 100 * -0.016462635 / -0.5487545 # observed on the field, in a real-world situation print 'float f:', f # 3.0 print 'int f:', int(f) # 2

It is normall behavior of float type (also in other languages with this type, like C):

>>> f = 100 * -0.016462635 / -0.5487545
>>> f
2.9999999999999996
>>> print f
3.0
>>> int(f)
2

int() just truncates everything after a comma. Use round() instead.

Lucas-C commented 8 years ago

Agreed, but I actually shouted WAT?? on this one.

cosmologicon commented 8 years ago

Nice. Some good finds here. That dictionary one is especially surprising. Looks like it also works with bool/int/floats that hash equal. I'm thinking of this one as a new quiz question:

>>> x, s = ???
>>> s.add(x)
>>> type(x) in map(type, s)
False

where one answer is x, s = 1, {True}.

So far I've gone with wats that only use builtins. I haven't gone into the standard library yet, but I'm thinking about adding a separate section for that. The id-related ones I'm guessing depend on the implementation, but there should be a place for that too. I'll keep this open in the meantime. Thanks!

Lucas-C commented 8 years ago

Glad I could help :)