Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient in Python: standard imports or contextual imports?

Tags:

python

I apologize in advance if this question seems remedial.

Which would be considered more efficient in Python:

Standard import

import logging

try:
  ...some code...
exception Exception, e:
  logging.error(e)

...or...

Contextual import

try:
  ...some code...
exception Exception, e:
  import logging
  logging.error(e)
like image 356
Huuuze Avatar asked Dec 08 '22 08:12

Huuuze


1 Answers

Contextual imports are technically more efficient, but I think they can create other problems.

Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.

like image 175
JimB Avatar answered May 14 '23 23:05

JimB