python from package import module, any problem with this?

Viewed 76

In my python code, I used "from packageA import moduleA". And my supervisor commented that this is very dangerous. He said the correct way is to do "import packageA.moduleA as moduleA".

Any comments? Is this really dangerous? Or its more like a common practice?

2 Answers

I think the use of import depends specific on the project, because in some situations you can import from a module / package.

From python documentation:

Package: A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an path attribute.

Module: An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.

https://docs.python.org/3/reference/import.html

So I see it like this:

Your import from packageA import moduleA is more apropriate when you import a variable from module for example from math import pi.

What I suspect is that you are trying to import from a package (considering that a package contains submodules you need to call them properly to achive the correct path of the submodule and also be summoned where is needed). As an example assuming that your package name is World which contains the following files (submodules) in this hierarchy Europe\Spain the import will be from World.Europe import Spain

I don't really work in the industry and practice programming as a hobby, so I am not qualified to talk about professionalism, but personally, I see absolutely no problem with from A import B apart from the fact that it may create a bit of confusion when referencing B in your code, for example:

from math import pi

print(pi)

versus:

import math

print(math.pi)

The second version makes it easier to understand where pi came from. This is also useful because there could be a function/method with the same name in multiple libraries that you are importing. One such example of this is the escape() function in both the html and glob libraries in Python.

from html import escape
from glob import escape

print(help(escape))

The above code would print out the escape() function of the glob library because it was most recently imported from there.

import html
import glob

print(help(html.escape))
print(help(glob.escape))

The above code differentiates between which one you're using.

This could also work:

from html import escape as h_escape
from glob import escape as g_escape

print(help(h_escape))
print(help(g_escape))

This above code also differentiates between the two things. But, again, I'm no industry expert, so I wouldn't know anything about the demands of it; but personally, I don't see any problem with it myself.

P.S. I got all of this from here: 5 Common Python Mistakes and How to Fix Them - Corey Schafer

Related