What is a function parameter =[] for?

Chris Angelico rosuav at gmail.com
Tue Nov 24 19:56:45 EST 2015


On Wed, Nov 25, 2015 at 11:36 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> If, and only if, the tuple
> contains nothing but immutable constants e.g.
>
> (1, 2.0, None, "spam")
>
> then a sufficiently smart compiler may be able to treat that specific tuple
> as a constant/literal. But that's a special case, and cannot be generalised
> to all tuple displays.

In which case it's simply an example of constant-folding. It's the
same as (1+2j) being called up with LOAD_CONST, despite being an
expression. Recent CPythons are even willing to change what data type
something is, to make it a constant:

>>> dis.dis(lambda x: x in ["a","b","c","d","e"])
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               6 (('a', 'b', 'c', 'd', 'e'))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE
>>> dis.dis(lambda x: x in {"a","b","c","d","e"})
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               6 (frozenset({'d', 'c', 'a',
'e', 'b'}))
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE

Lists and sets are definitely not constants. Tuples and frozensets
aren't literals, but they can be constant. This is the optimizer
talking, though, not language semantics.

ChrisA



More information about the Python-list mailing list