Creating a List of Empty Lists

Skip Montanaro skip at pobox.com
Sat Dec 6 18:50:27 EST 2003


    Emile> But does intern() intern?  

Yes, I believe it does:

    >>> intern('foo bar')
    'foo bar'
    >>> a = 'foo bar'
    >>> a is 'foo bar'
    0
    >>> a = intern(a)
    >>> a is 'foo bar'
    0
    >>> a is intern('foo bar')
    1
    >>> a = 'foo_bar'
    >>> a is 'foo_bar'
    1

    Emile> does it _only_ apply to strings that look like identifiers?  

Automatic interning, yes.  At the point where the system has to decide
whether to automatically intern a string it knows nothing about the higher
level context in which the string appears.  The optimization was added
because the strings which are manipulated most often by the interpreter
happen to be those which represent the program's identifiers (object
attributes, variables, etc).  Consequently, the decision was made some time
ago to simply intern all strings which look like identifiers (as the snippet
above shows).  It's a bit like driving a tack with a sledge hammer, but it
does improve interpreter performance.

    Emile> How else might you know?

It doesn't really matter.  The intern() function is available to programmers
who want to conciously optimize their string handling and is properly
documented.  Automatic interning is not an optimization aimed at the
programmer, but at the internals of the interpreter.  It's just a side
effect of the crude optimization that if you happen to use a string literal
in your program which looks like an identifier, it's interned
automatically.  Look at is as a freebie. ;-)

Skip





More information about the Python-list mailing list