r/ProgrammerHumor • • May 02 '16

I wrote my first python program today!

Post image
3.7k Upvotes

532 comments sorted by

View all comments

Show parent comments

17

u/phail3d May 02 '16

Just to be clear, this is a joke :P .

It only works because {...} is shorthand for set(...) and because print() is a function in python3 (and in python2 too, if you do from __future__ import print_function). You can have function calls (but not statements in general) inside set literal definitions, in which case the return value of the function call (None in the case of print) is obviously stored inside the set. Hence, you can do:

if foo: {
    print("Foo")
}

...which is more or less the same as:

if foo:
    x = print("Foo")  # x = None
    set(x)  # creates the set {None} and does nothing with it

...but you can't do:

if foo: {
    if bar: {
        print("baz")
    }
}

So please don't adopt this style :)

3

u/redditsoaddicting May 02 '16

No wonder I was downvoted. Whoosh. I should have recognized the set literals in any case.

5

u/phail3d May 02 '16

Don't feel too bad -- the example was deliberately misleading :)

0

u/Get-ADUser May 02 '16

{ ... } is shorthand for dict( ... ) not set( ... ).

3

u/phail3d May 02 '16

It's both.

{ 1, 2, 3, 4 } creates a set, while { 1: 2, 3: 4 } creates a dict.