Question: Python 2 and 3 compatible way to call intern()

Question

Python 2 and 3 compatible way to call intern()

Answers 2
Added at 2016-12-05 06:12
Tags
Question

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)?

Answers to

Python 2 and 3 compatible way to call intern()

nr: #1 dodano: 2016-12-05 06:12

Same as always.

try:
  intern
except NameError:
  from sys import intern
nr: #2 dodano: 2016-12-05 06:12
try:
    from sys import intern
except ImportError:
    pass

This should work on both.

Source Show
◀ Wstecz