What is the different between import library as lib and from library import (....)? I saw people used from library import (....) and import library as lib. And wonder which one is the best practice.
Can you help me? Thank you.
What is the different between import library as lib and from library import (....)? I saw people used from library import (....) and import library as lib. And wonder which one is the best practice.
Can you help me? Thank you.
There is no functional difference between the two, but for aesthetics, readability and maintainability reasons there are subtle pros and cons to both.
Some common considerations:
lib.func instead of just func. In this case it would make the code look cleaner to import the name from the module so that the name can be used without the module name. For example, if you have a complicated formula such as y = sqrt(cos(x)) - sqrt(sin(x)), you don't want to make the code look more complicated than it already is with y = math.sqrt(math.cos(x)) - math.sqrt(math.sin(x)).from lib import a, b, c, d... statement. For example, it is common to just import ast for syntax tree traversal since many cases of ast involve references to well over 10 node types, so a simple import ast is usually preferred over an excessively long statement of from ast import Module, Expression, FunctionDef, Call, Assign, Subscript, ....import ast.from re import search because search is such a commonly used name, and there may very well be a local variable named search or a function named search imported from another module to cause name collisions.search(...) makes your code less readable than writing re.search(...) also because search is too generic a term. A call to re.search makes it clear that you're performing a regex search while a call to search looks ambiguous. So use from lib import a only when a itself is a specific term, such as from math import sqrt.