Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any point in using relative paths in Python import statement?

I have a Python package called Util. It includes a bunch of files. Here is the include statements on top of one of the files in there:

from config_util import ConfigUtil #ConfigUtil is a class inside the config_util module
import error_helper as eh

This works fine when I run my unit tests.

When I install Util in a virtual environment in another package everything breaks. I will need to change the import statements to

from Util.config_util import ConfigUtil
from Util import error_helper as eh

and then everything works as before. So is there any point in using the first form or is it safe to say that it is better practice to always use the second form?

If there is no point in using the first form, then why is it allowed?

like image 511
Barka Avatar asked Nov 07 '22 23:11

Barka


1 Answers

Just wrong:

from config_util import ConfigUtil
import error_helper as eh

It will only work if you happen to be in the directory Util, so that the imports resolve in the current working directory. Or you have messed with sys.path using some bad hack.

Right (using absolute imports):

from Util.config_util import ConfigUtil
import Util.error_helper as eh

Also right (using relative imports):

from .config_util import ConfigUtil
import .error_helper as eh

There is no particular advantage to using relative imports, only a couple of minor things I can think of:

  • Saves a few bytes in the source file (so what / who cares?)
  • Enables you to rename the top level without editing import statements in source code (...but how often do you do that?)
like image 129
wim Avatar answered Nov 15 '22 11:11

wim