Why is it impossible to mix Python2 with Python3?

╄→гoц情女王★ 提交于 2020-12-11 10:17:09

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/44406320/why-is-it-impossible-to-mix-python2-with-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!