How do I write code that uses Python's intern
that will work (be compatible) with both Python 2 and Python 3? Is there a clean way to do it?
In Python 2, intern is a builtin, so you use intern()
. In Python 3, it has been moved to the sys
module, so you're supposed to use sys.intern()
. It seems that intern()
works on Python 2 but not Python 3, and sys.intern()
works on Python 3 but not Python 2. Is there any clean syntax that will work on both Python 2 and Python 3, without using version detection (ugly)?
try:
from sys import intern
except ImportError:
pass
This should work on both.
With six
package:
from six.moves import intern