I\'ve tried to find a comprehensive guide on whether it is best to use import module
or from module import
. I\'ve just started with Python and I\'m
As Jan Wrobel mentions, one aspect of the different imports is in which way the imports are disclosed.
Module mymath
from math import gcd
...
Use of mymath:
import mymath
mymath.gcd(30, 42) # will work though maybe not expected
If I imported gcd
only for internal use, not to disclose it to users of mymath
, this can be inconvenient. I have this pretty often, and in most cases I want to "keep my modules clean".
Apart from the proposal of Jan Wrobel to obscure this a bit more by using import math
instead, I have started to hide imports from disclosure by using a leading underscore:
# for instance...
from math import gcd as _gcd
# or...
import math as _math
In larger projects this "best practice" allows my to exactly control what is disclosed to subsequent imports and what isn't. This keeps my modules clean and pays back at a certain size of project.