Code Monkey home page Code Monkey logo

wtfpython's People

Contributors

1f604 avatar 64kramsystem avatar abdnh avatar bwduncan avatar cben avatar cclauss avatar charettes avatar cl0ne avatar dos1 avatar fluencydoc avatar frontdevops avatar haksell avatar hippiezhou avatar imba-tjd avatar jongy avatar josedefreitas avatar kannes avatar larsks avatar nitmir avatar nucaranlaeg avatar rec avatar satwikkansal avatar sgnn7 avatar sobolevn avatar sohaibfarooqi avatar ss18 avatar umutambyi-gad avatar vibhu-agarwal avatar vitorsrg avatar weyzu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wtfpython's Issues

Nitpicking and minor suggestions

3 --0-- 5 == 8 and --5 == 5 are both semantically correct statements and evaluate to True.

Might want to add that ++a and --a are both valid Python (given a is a number), but isn’t what you probably think they are (increment/decrement).

'a'[0][0][0][0][0] is also a semantically correct statement as strings are iterable in Python.

This is possible because strings are sequences, not iterables (although they are iterables as well).

Multiple Python threads don't run concurrently (yes you heard it right!).

This is not accurate. Python threads do run concurrently, but can’t run Python code concurrently. A thread can execute if another is in the middle of non-Python code execution (e.g. waiting for the response of a network call).

Regarding that TODO pypi package.

How about we show a random example every time the command is executed in command line? I guess it's more fun/useful than showing all at once. I can create a PR if you like.

Help to make the collection more interesting

The aim of this project to make the readers aware of the intricacies of Python in as interesting manner as possible. Anyone is more than welcome to help and enhance this awesome project by

  • Suggesting fancy titles for the existing examples.
  • Suggesting more tricky snippets for the existing examples.
  • Suggesting new examples (Don't worry, You'll be given due credits for your treasury examples 😅 )

Typo in python code

At one point in the README.md, you state:

>>> a = "some_string"
140420665652016
>>> id(a)
>>> id("some" + "_" + "string") # Notice that both the ids are same.
140420665652016
...

but I believe the correct order would be

>>> a = "some_string"
>>> id(a)
140420665652016
>>> id("some" + "_" + "string") # Notice that both the ids are same.
140420665652016
...

Feature request: trying to change the index variable in a for loop

Hello! After finding a link to your project today on reddit I have decided to give another go at a previous project of mine, now using your document format as inspiration! While doing my research I have come across something that I think would fit well in your list. Here it is:

for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range

This is taken from the Python manual itself, which in itself makes it notable. This might not come as a surprise to anyone who started coding with Python - but for people coming from C++, Java or similar, this is very much something they'd expect to work, giving how for loops work in these languages.

Hope you like this :) Source: https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

By the way, if you have the time to read my own work and maybe let me know if I'm missing anything, I'd be very honored to have you onboard! Here is the link for my current work-in-progress version: https://github.com/tukkek/notablepython/blob/master/README.md

Let's meet Friendly Language Uncle For Life

The example worked in interpreter but not when I write in a .py file.

from __future__ import barry_as_FLUFL
import sys
print(sys.version)
"Ruby" != "Python" #This is OK
from __future__ import barry_as_FLUFL
import sys
print(sys.version)
"Ruby" <> "Python" #But this  raise a exception

output 1:

3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]

output 2:

  File "test.py", line 4
    "Ruby" <> "Python"
            ^
SyntaxError: invalid syntax

Output of "A tic-tac-toe where X wins in the first attempt!" is wrong.

Link here

The last paragraph of the section claims the following output:

>>> board = [(['']*3)*3] # board = = [['']*3 for _ in range(3)]
>>> board[0][0] = "X"
>>> board
[['X', '', ''], ['', '', ''], ['', '', '']]

However, the results I get from Python 2.7.15rc1 (Ubuntu 18.04), Python 3.6.5 (Ubuntu 18.04) and Python 3.5.2 (Ubuntu 16.04) are all the same and are different from what this doc days. It is:

[['X', '', '', '', '', '', '', '', '']]

Furthermore, I tried multiple ways of arranging the parentheses and couldn't get the said result. All results I have are

>>> board
[['X', '', ''], ['X', '', ''], ['X', '', '']]

An interactive website

Hey all!

It's exciting to announce that "What the f*ck Python!" has been selected as a project for GirlScript Summer of Code.

Rough ideas regarding what to work upon this summer are there in this doc.

Once we're assigned project mentors, the next steps I guess should to come up with a detailed design for the same, and break down into smaller issues so that multiple participants new to the Open Source world can work upon at the same time.

If there are any ideas that you have, feel free to discuss in this thread or in the above doc or email. All this started out as a fun project, and its amazing to see how the content here has evolved with time. The ultimate vision I think of is to make this a super helpful resource to learn about intricacies of Python in an interesting way. Let's see how far we can go with this. Hoping for an exciting summer for wtfpython! 🎉

Add this to the explanation in "https://github.com/satwikkansal/wtfpython#-backslashes-at-the-end-of-string"

From SO post - https://stackoverflow.com/questions/647769/why-cant-pythons-raw-string-literals-end-with-a-single-backslash

String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r""" is a valid string literal consisting of two characters: a backslash and a double quote; r"" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

Few examples :

>>> print(r"\"")
\"
>>> print(r"A\nB")
A\nB
>>> print(r"A\\nB")
A\\nB
>>> print("A\nB")
A
B
>>> print("A\\nB")
A\nB
>>> print("A\\\nB")
A\
B

Explicit Typecast Of Strings Quibble

In my python 2.7 interpreter I get a different output:

50/a #Example version
0
50/a #My version
0.0

Not sure if that's a version thing, a typo, or something else.

Charmap codec Error

Hi there, thanks for the amazing repository.....
But I am not able to run it on Python 3.6.3 it throws the Unicode decode error: 'charmap' codec can't decide byte 0x90....

"Let's make a giant string!" code example is not representative

add_string_with_plus() and add_string_with_join() take the same time in the example. It implies that CPython's += optimization is in effect (unrelated to the example in the very next section with a possibly misleading title: "String concatenation interpreter optimizations" -- the example is more about string interning, string literals than string concatination -- the linked StackOverflow answer explains it quite well).

The explanation in "Let's make a giant string!" claims quadratic behavior for str + str + str + ... in Python (correct) but the example add_string_with_plus() uses CPython += optimizations -- the actual times are linear on my machine (in theory the worst case is still O(n2) -- it depends on realloc() being O(n) in the worst case on the given platform -- unlike for Python lists x1.125 overallocation (add_string_with_join() is linear) is not used for str):

In [2]: %timeit add_string_with_plus(10000)
1000 loops, best of 3: 1.1 ms per loop

In [3]: %timeit add_string_with_format(10000)
1000 loops, best of 3: 539 µs per loop

In [4]: %timeit add_string_with_join(10000)
1000 loops, best of 3: 1.1 ms per loop

In [5]: L = ["xyz"]*10000

In [6]: %timeit convert_list_to_string(L, 10000)
10000 loops, best of 3: 118 µs per loop

In [7]: %timeit add_string_with_plus(100000)
100 loops, best of 3: 11.9 ms per loop

In [8]: %timeit add_string_with_join(100000)
100 loops, best of 3: 11.8 ms per loop

In [9]: %timeit add_string_with_plus(1000000)
10 loops, best of 3: 121 ms per loop

In [10]: %timeit add_string_with_join(1000000)
10 loops, best of 3: 116 ms per loop

Increasing iters x10, increases the time x10 -- linear behavior.

If you try the same code with bytes on Python 3; you get quadratic behavior (increasing x10 leads to x100 time) -- no optimization:

In [11]: def add_bytes_with_plus(n):
    ...:     s = b""
    ...:     for _ in range(n):
    ...:         s += b"abc"
    ...:     assert len(s) == 3*n
    ...:     

In [12]: %timeit add_bytes_with_plus(10000)
100 loops, best of 3: 10.8 ms per loop

In [13]: %timeit add_bytes_with_plus(100000)
1 loop, best of 3: 1.26 s per loop

In [14]: %timeit add_bytes_with_plus(1000000)
1 loop, best of 3: 2min 37s per loop

Here's a detailed explanation in Russian (look at the timings, follow the links in the answer).

Add section explaining 'yield' in list comp/generator exp

These examples illustrate what for me is one of the most confusing behaviours in the whole of Python:

>>> [(yield x) for x in ('a','b')]
<generator object <listcomp> at 0x7f69d5379ba0>
>>> list([(yield x) for x in ('a','b')])
['a', 'b']
>>> list((yield x) for x in ('a','b'))
['a', None, 'b', None]

A relevant SO question and bug report

Cannot reproduce "wtf"*bool example

In Part 3 of "What is wrong with booleans?" there's the following example:

>>> some_bool = True
>>> "wtf"*some_bool
'wtf'
>>> "wtf"*some_bool
''

I'm unable to reproduce this with either 2.7.10 nor 3.6.4:

Python 2.7.10 (default, Jul 15 2017, 17:16:57) 
IPython 5.5.0 -- An enhanced Interactive Python.

In [1]: some_bool = True

In [2]: "wtf"*some_bool
Out[2]: 'wtf'

In [3]: "wtf"*some_bool
Out[3]: 'wtf'    

Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: some_bool = True

In [2]: "wtf"*some_bool
Out[2]: 'wtf'

In [3]: "wtf"*some_bool
Out[3]: 'wtf'

Great work collecting all these examples. Thank you for doing this.

Tricky SyntaxErrors

These are some of my treasures, discovered while implementing a Python parser years ago.

First, the "surprising comma."

Codepad: http://codepad.org/JiFQi7vr

def f(**args, **kwargs):
 print args, kwargs

def args = 5, 7
f(42, *args,)

Technically only f(*args,) or f(**kwargs,) is needed to tickle this one.

Second, the "not knot."

Codepad: http://codepad.org/IA7k5jEg

x = True
y = False

print not x == y
print x == not y

Again, a smaller test case, like x == not y, will provoke it.

A few suggestions

Hi.

Just a few "gotcha" suggestions from my personal collection ^^
Tell me which ones are worth a PR:

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

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

# Python 2 only, found it myself
f = 100 * -0.016462635 / -0.5487545  # observed on the field, in a real-world situation
print '            f:', f              # 3.0
print '       int(f):', int(f)         # 2
print '     floor(f):', floor(f)       # 2.0

# Name mangling:
class Yo(object):
    def __init__(self):
        self.__bitch = True
Yo().__bitch  # AttributeError: 'Yo' object has no attribute '__bitch'
Yo()._Yo__bitch  # True

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

json.loads('[NaN]') # [nan]
json.loads('[-Infinity]') # [-inf]

int('١٢٣٤٥٦٧٨٩') # 123456789 - cf. http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/

# Implicit type conversion of keys in dicts
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

# Those final ones are taken from cosmologicon Python wats quiz
'abc'.count('') == 4
1000000 < '' and () > []  # "objects of different types except numbers are ordered by their type names"
False == False in [False]

[3,2,1] < [1,3]  # False
[1,2,3] < [1,3]  # True

x, y = (0, 1) if True else None, None # -> ((0, 1), None)
x, y = (0, 1) if True else (None, None) # -> (0, 1)

A kind suggestion

Can you please make it explicit which Python version produces these "what the heck" results?

I have tested the very first example, named Skipping Lines and produces 32 instead of 11.

This behavior you produce is for Python 2.7.

Consume generator expression after updating the iterable

Hi,
I have submitted a PR for which I want input from the community. Let me summarise the code example that I have submitted:

 >>>  iter1 = [1,2,3,4]
  >>> g1 = (x for x in iter1)
  >>> iter1 = [1,2,3,4,5]
  >>> list(g1)
  >>> [1,2,3,4]

  >>> iter2 = [1,2,3,4]
  >>> g2 = (x for x in iter2)
  >>> iter2[:] = [1,2,3,4,5] 
  >>> list(g2)
  >>> [1,2,3,4,5]

This is basically consuming the generator after updating the provided iterable. The main difference in two examples in mainly how they updated the elements of iterable. First one uses =(Assignment Operator) and second one used [:]=(Slice Assignment). Assignment creates a new list thats why output of generator is not changed, whereas slice assignment updated the list iteself thats why generator outputs the updated list.

@satwikkansal suggested that Evaluation time discrepancy is similar to the one
I submitted and asked me to open an issue so that we can have discussion on this one.

What do you guys think? Any suggestions/improvements/critique?

Thanks,
Sohaib

Slight wording issue in README

If join() is a method on a string then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic list.

Also, it's string specific, and it sounds wrong to put a string-specific method on a generic list.

Notice the string-specific part is duplicated in the last two sentences.

Typo in CONTRIBUTING.md

Adding spell is wrong.

If you're ading a new example, please do create an issue before submitting a patch.

Deleting your own variables

Found something new for you! So it turns out you can run this code:

def outer(x):
    del x
    return x

outer(1)

'''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in outer
UnboundLocalError: local variable 'x' referenced before assignment
'''

Not sure you'll want to add it to the list because it's unlikely anyone would do that - but it is technically interesting in itself because as far as I know Python is the only language that will let you destroy a local variable (or even function argument!) instead of just letting it expire and be garbage-collected when the current context is destroyed (like when leaving the function or an "except" block). By mistyping, you could easily delete a variable that should, by all means, be there and be left with a "wtf just happened to my poor dear x?" T_T

Also keep in mind that this can create very confusing scenarios, especially since the __del__() special method can be implemented in any class. Think about this: you try to del x from inside your method - except that the actual __del__() function is never called - because it is not called when del is issued but when all reference counts are extinguished and the instance is garbage-collected. So if you pass x to a function as a parameter, it will still have (at least) one reference holding the instance in memory outside of the function itself!

I'll let you come up with a clever, fun code example to show this if you think that this is worthy of adding to the your list :)

Explanation for "Time for some hash brownies!" is insufficient

The current explanation seems to imply that any two values with equal hashes will take up the same slot in the dict. This is, fortunately, not true.
example:

>>> d = {}
>>> a = float('NaN')
>>> b = 0
>>> d[a] = 1
>>> d[b] = 2
>>> d
{nan: 1, 0: 2}
>>> hash(a) == hash(b)
True

The actual reason 0.0 overwrites 0, is that they are equal.

>>> 0.0 == 0
True

I don't quite know how to put all that concisely, without losing the interesting lesson about hash values.
Any suggestions welcome.

Feature request: Complicated variable assignment in for loops

Normally in a for loop, you just do for <variable_name> in iterable:, but you can also do use anything that is a valid assignment target (An "lvalue" in C). Like for f()(g)[t].x in seq: is perfectly valid syntax.

Here is a draft:


For what?

d = {}
for d['n'] in range(5):
    print(d)

Output:

{'n': 0}
{'n': 1}
{'n': 2}
{'n': 3}
{'n': 4}
def indexed_dict(seq):
    d = {}
    for i, d[i] in enumerate(seq):
        pass
    return d

Output:

>>> indexed_dict(['a', 'b', 'c', 'd'])
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> indexed_dict('foobar')
{0: 'f', 1: 'o', 2: 'o', 3: 'b', 4: 'a', 5: 'r'}

💡 Explanation:

  • A for statement is defined in the Python grammar as:

    for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
    

    Where exprlist is the assignment target. This means that the equivalent of {exprlist} = {next_value} is executed for each item in the iterable.

  • Normally, this is a single variable. For example, with for i in iterator:, the equivalent of i = next(iterator) is executed before every time the block after for is.

  • d['n'] = value sets the 'n' key to the given value, so the 'n' key is assigned to a value in the range each time, and printed.

  • The function uses enumerate() to generate a new value for i each time (A counter going up). It then sets the (just assigned) i key of the dictionary. For example, in the first example, unrolling the loop looks like:

    i, d[i] = (0, 'a')
    pass
    i, d[i] = (1, 'b')
    pass
    i, d[i] = (2, 'c')
    pass
    i, d[i] = (3, 'd')
    pass

Explanations for "Strings can be tricky sometimes!" are incomplete

The main issue is that they do not address the third snippet at all, "a" * 20 vs "a" * 21.

I'm also very curious to know /why/ it's the case that

Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why 'wtf!' was not interned due to !.

If it were just non-ASCII, that would make some sense, but what problems could interning a string with an exclamation point cause?

discrepancy about "Evaluation time discrepancy"

Hi,

I am testing about the interesting Evaluation time discrepancy, and I have a test like following:

a = [1, 2, 3]
b = [10, 20, 30]
g = (i + j for i in a for j in b)
a = [4, 5, 6]
b = [100, 200, 300]
print(list(g))

And the result is

[101, 201, 301, 102, 202, 302, 103, 203, 303]

I tested it with python3 on osx and debian, and got same result.

It seems that only a is evaluated at declaration time? Or passed by reference?
Could someone give some detailed information about this?

InputRequired(), the message para doesn't work

WTForms (2.1)
Flask-WTF (0.14.2)
Flask-Bootstrap (3.3.7.1)
Flask (0.12.2)

I define the login form by:

class LoginForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(
        message="enter the username"), Length(min=6, max=16, message="Length should be more than 6 and less than 15")])
<---ommited--->

route.py return the render html page, and the page was implemented by wtf.quick_form.

result:
Length messges field works, but InputRequired always shows the prompt: "Please fill out this field"

expectation:
parameter: message of InputRequired should works.

return or break statement in a finally block

Hello. What do you think, is the following a wat?

https://docs.python.org/3/reference/compound_stmts.html#the-try-statement:

If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. ... If the finally clause executes a return or break statement, the saved exception is discarded.

Example:

while True:
    try:
        1/0
    except Exception:
        raise
    finally:
        break     # discards the exception

print('hell')     # it does print indeed

Ebook version?

Hey guys,

I was preparing a pdf for the collection, while a friend of mine recommended me to put in some extra effort to release an ebook version for the same.

I have absolutely no experience with this and I doubt if it'd be an overkill. That's why I've opened up this issue, maybe someone having prior experience with all this can help me in figuring out what to do and if it actually makes sense to do so 😅

Question regarding "Let's see if you can guess this?" explanation?

Hi,
Regarding the example:

a, b = a[b] = {}, 5

In the document, it is said that "After the expression list is evaluated, it's value is unpacked to the target lists from left to right.".
If I get it right, there is two "target list" in the example, a, b and a[b], and one expression {}, 5

So, if we break down the example, why it's not:

a, b = {}, 5
a[b] = {}, 5

Can you enlighten me a little here?

Thanks a lot!
Guillaume

Some Unicode characters look identical to ASCII ones

In the 'Skipping lines' example (the first one), the following explanation is given as to why the two 'value' variables name aren't the same:

Some Unicode characters look identical to ASCII ones, but are considered distinct by the interpreter.

Imho this paints the wrong picture. ASCII is an encoding, Unicode is a character collection. ASCII isn't a synonym for the English alphabet. In Python 3, all strings are Unicode, it has lost the relation to any legacy encoding, and ASCII will fall more and more into disuse. The point the example tries to make is that certain Unicode characters are homoglyphs, and that those homoglyphs to an English alphabet character can provide a pitfall for an agnostic reader. I think it should read something like:

Some non-Western characters look identical to letters in the English alphabet, but are considered distinct by the interpreter. For example the Cyrillic 'е' (Ye) and the Latin 'e', which can be demonstrated by using the built-in ord() function, that returns a character's Unicode code point:

Then also the second code snippet can feature an actual different example than the first one instead of repeating the same value = something:

>>> ord('е') # cyrillic Ye
1077
>>> ord('e') # latin, as used in English
101
>>> 'е' == 'e'
False

Accessibility: image background and alt description

  • When reading the Markdown file with an application with dark background, or when using dark background in Github (with browser modules etc.), somes images are not legible.
  • Images doesn’t have an alt= for people using screen reader (I can do that if you want).

"Deleting a list item while iterating over it" has improper example or explanation

In the "Deleting a list item while iterating over it" trick, in the list_1 example, del actually deletes the item variable name. The name will be reassigned to the next value on the next iteration, but will be absent up to the end of the code block after the del item statement. No operator even tries to delete from the list_1, and the list remains unaffected.

There are 2 possible ways to fix this:

  1. Either you meant del list_1[idx] in the example, which removes the indexed item from the list. And the output will be [2, 4] for the same reason as with list_4.pop(idx).
  2. Or the explanation is wrong, and should not refer to item deletion, but should refer to the variable name un-assignment.

Just for historic reference, this is how the example looks now:

list_1 = [1, 2, 3, 4]
for idx, item in enumerate(list_1):
    del item
>>> list_1
[1, 2, 3, 4]
* del removes a specific index (That's why first list_1 was unaffected), raises IndexError if an invalid index is specified.

python 3.0+ Ellipsis

python2:

>>> Ellipsis
Ellipsis

python3:

>>> ...
Ellipsis
>>> Ellipsis
Ellipsis

... and pass

>>> def test():
               ...  # or pass
>>> a = [1, 2, 3, 4, 5]
>>> a.append(a)
>>> print(a)
[1, 2, 3, 4, 5, [...]]

''.split() != ''.split(' ')

Hello. Does the following qualify?
When you split an empty string without arguments, you get an empty list.
When you specify a separator, you get a non-empty list, see below.
More of an inconsistency than a wtf, but nevertheless I'd like to share this.
I wonder why it works this way.

>>> ''.split() != ''.split(' ')
>>> True

>>> ''.split() 
>>> []

>>> ''.split(' ')
>>> ['']

Add more snippets related to string interning

>>> a = "foo" # second snippet
>>> b = "foo"
>>> a is b
True

>>> a = "foo!"
>>> b = "foo!"
>>> a is b
False

>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' # third snippet
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False

problem in "The mysterious key type conversion" explanation

At last point

  • For the desired behavior, we can redefine the __eq__ method in SomeClass

    class SomeClass(str):
      def __eq__(self, other):
          return (
              type(self) is SomeClass
              and type(other) is SomeClass
              and super().__eq__(other)
          )
    
      # When we define a custom __eq__, Python stops automatically inheriting the
      # __hash__ method, so we need to define it as well
      __hash__ = str.__hash__
    
    some_dict = {'s':42}

    Output:

    >>> s = SomeClass('s')
    >>> some_dict[s] = 40
    >>> some_dict
    {'s': 40}
    >>> keys = list(some_dict.keys())
    >>> type(keys[0]), type(keys[1])
    (__main__.SomeClass, str)

some_dict output {'s': 42, 's': 40} in Python 3.6.5/3.5.5/3.4.8/2.7.15, can someone provide which version output {'s': 40}?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.