简体   繁体   中英

Why is it impossible to mix Python2 with Python3?

Despite all that has been said and written on Python2 vs Python3, I have been unable to identify why the developers made it impossible to mix Python2 and Python3 code. Surely there must be a reason for this?

In Fortran, for instance, the many versions are incompatible with each other, but they can still happily co-exist within the same project. The same applies to C and C++: some C code is not compatible with C++, but the compiler is able to recognize the correct language using the file extension. Is there a specific reason for why this approach was not chosen for Python3? That is, let Python3 modules be identified by a .py3 extension (or a shebang comment), and use one single interpreter for both .py and .py3 code?

EDIT:

There is already a question named Why is Python 3 not backwards compatible? , but this question is different. I know that Python 3 introduces new features and breaks backwards compatibility because of this. It still does not mean that Python 2 and 3 cannot coexist the same way C and C++ can.

You can't mix python2 and python3 in the same project, because:

  1. The interpreters are different. You're either running an interpreter for python2, or for python3. I don't know of any current interpreter that dynamically chooses the python2 or python3 runtime.
  2. The syntax is (slightly) different.
  3. The types are different.

However, you could certainly run both the python2 and python3 runtimes and use some sort of (IPC) message passing between them.

With the case of C, and C++, you can run them in the same process, so that's fine. Incidentially, you can run python and C (or C++) in the same process, too.

The only way I can think of that would allow you to run python2 and python3 in the same process would be to embed both runtimes in the same process, however, they will very likely clobber each other's globals and get confused.

Is there a specific reason for why this approach was not chosen for Python3? That is, let Python3 modules be identified by a .py3 extension (or a shebang comment), and use one single interpreter for both .py and .py3 code?

Because it's completely unnecessary! With the help of modules like six , it's quite easy to write code which is compatible with both Python2 and Python3 with no source-code changes. This isn't just a parlour trick; major projects like Django have been written this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM