Creating a List of Empty Lists

Skip Montanaro skip at
Sun Dec 7 00:50:27 CET 2003

    Emile> But does intern() intern?  

Yes, I believe it does:

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

    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. ;-)


More information about the Python-list mailing list