Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import some python3 modules in Python2

Is there a way to import Python 3 modules into Python 2 scripts? I want to use some Python 3 modules in a Django application and haven't seen anything on the Internet. Any clues?

like image 569
Antoine Pietri Avatar asked May 21 '12 17:05

Antoine Pietri


People also ask

Can PYTHON3 import python2 module?

Python 2 and Python 3 were never intended to be compatible internally. In fact, the reason Python 3 exists was to be able to make incompatible changes that would not normally be made in a minor version update, e.g. 2.6 to 2.7. This includes byte codes which may not be compatible even across minor versions.

Are Python 2 and 3 compatible with each other?

The latest stable version is Python 3.9 which was released in 2020. The nature of python 3 is that the changes made in python 3 make it incompatible with python 2. So it is backward incompatible and code written in python 3 will not work on python 2 without modifications.

Can two Python modules import each other?

Modules can import each other cyclically, but there's a catch. In the simple case, it should work by moving the import statements to the bottom of the file or not using the from syntax.


1 Answers

I don't think it's really possible, no. The same instance of the interpreter has to handle every module imported in a given app, so there's no obvious way to mix and match interpreters. If you need to accomplish a discrete task with a Python 3 module, you could try making a command-line script to accomplish your task and then calling that script as a subprocess from your Python 2 app, but that would be awkward to say the least.

Note that I don't think there are really a whole lot of Python 3-only modules -- most modules at this point either support both versions, or only Python 2.

like image 149
Andrew Gorcester Avatar answered Oct 06 '22 01:10

Andrew Gorcester