How to deal with python imports so they work easily with py2 and py3? -


i looking way write python packages , modules makes them python 3 friendly , makes easy import them.

most common case have 1 major class want provide users, call mycode.

your package named mycode , put body of mycode class mycode/mycode.py.

now, expect people 1 of these:

import mycode obj = mycode.myclass() 

or:

from mycode import myclass() obj = myclass() 

now, question should put inside __init__.py in order make work, in both python 2.6+ , 3.x.

use absolute imports, it'll work fine across python versions. inside mycode/__init__.py put:

from __future__ import absolute_import  mycode.mycode import myclass 

where __future__ import works python 2.5 , onwards; see pep 328. without absolute_import import, import mycode ambiguous; python 3 treat absolute , load top-level package, python 2 treats relative , import nested module instead.

the alternative use relative import:

from .mycode import myclass 

which work across same spectrum of versions.


Comments