Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What is the difference between these two import statements?

They both functionally looks same to me. Are there any differences and advantages of using one over another?

>>> from datetime import datetime, timedelta
>>> from datetime import (datetime, timedelta)
like image 448
Babu Avatar asked Nov 28 '22 16:11

Babu


2 Answers

If you wrap the imports in parens, you don't have to use a backslash for line continuation if you put a line break in the import statement, which is the preferred style. Functionally, they are identical, and if on one line, leaving out the parens is cleaner.

like image 77
Silas Ray Avatar answered Dec 05 '22 03:12

Silas Ray


Both of them are same:

In [17]: import dis

In [18]: def func1():
   ....:     from datetime import datetime, timedelta
   ....:     

In [19]: def func2():
   ....:     from datetime import (datetime, timedelta)
   ....:     

In [20]: dis.dis(func1)
  2           0 LOAD_CONST               1 (-1)
              3 LOAD_CONST               2 (('datetime', 'timedelta'))
              6 IMPORT_NAME              0 (datetime)
              9 IMPORT_FROM              0 (datetime)
             12 STORE_FAST               0 (datetime)
             15 IMPORT_FROM              1 (timedelta)
             18 STORE_FAST               1 (timedelta)
             21 POP_TOP             
             22 LOAD_CONST               0 (None)
             25 RETURN_VALUE        

In [21]: dis.dis(func2)
  2           0 LOAD_CONST               1 (-1)
              3 LOAD_CONST               2 (('datetime', 'timedelta'))
              6 IMPORT_NAME              0 (datetime)
              9 IMPORT_FROM              0 (datetime)
             12 STORE_FAST               0 (datetime)
             15 IMPORT_FROM              1 (timedelta)
             18 STORE_FAST               1 (timedelta)
             21 POP_TOP             
             22 LOAD_CONST               0 (None)
             25 RETURN_VALUE      
like image 38
Ashwini Chaudhary Avatar answered Dec 05 '22 04:12

Ashwini Chaudhary