1

Recently, an issue with the Python import statements struck me.

Problem: I have a package say foo containing a module bar which I need to refer as spams.

There are 2 ways I can perform this operation:

Method-01: import foo.bar as spams

Method-02: from foo import bar as spams

The first method is what I generally use and the alternate method is what I discovered. But I realised that the 2nd method is a bit more "explicit".
I would like to know what are the differences between the two methods(if any) with regards to:

  • Efficiency
  • Pythonic code
  • Convention
Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71

1 Answers1

2

Regarding first and third point, here you can find all information about it.

A slightly special case exists for importing sub-modules.

The statement:

import os.path

stores the module os locally as os, so that the imported submodule path is accessible as os.path. As a result:

import os.path as p

stores os.path , not os , in p .

This makes it effectively the same as:

from os import path as p

As you can see it is officially documented that efficiency and convention doesn't matter here.

As for more pythonic code: from my experience, I mostly see

import foo.bar as spams

I think that this is because of readability, however it depends on the team you are working on.

MaLiN2223
  • 1,290
  • 3
  • 19
  • 40