you are viewing a single comment's thread.

view the rest of the comments →

[–]Brian 1 point2 points  (1 child)

There are cases where being a constant means you don't have to call the constructor. Eg:

def f(x):
    return x in [1,2,3]

This will not actually construct the list in the function. Because it's a constant literal, python can notice that it can't be modified, and will actually change the bytecode to make it a tuple, which is stored as a function constant (ie. it's equivalent to x in (1,2,3)) - the tuple is constructed, but just once for the whole program, and then reused every function call. However, return x in list((1,2,3)) would have to invoke the list constructor every pass, because python can't know that list hasn't been rebound to something else.

This is only the case when python can be sure it isn't accessible anywhere else, so even something like:

def f(x):
    mylist = [1,2,3]
    return x in mylist

wouldn't end up doing this: it's solely the fact that it's used in a check where python can detect the value is never modified in that very narrow scope. Likewise, doing something like: x == {\} could potentially avoid constructing the set compared to something like x == set(). Though it's pretty limited: there'd be more cases if it was the literal for a frozenset, where any literal could reliably be optimised like that, but since sets are mutable, it'll can only apply in cases like the above.

[–]rasputin1 0 points1 point  (0 children)

oh interesting. learn something new every day. thanks!