0

Given code such as

def norm(x, y):
    from math import sqrt
    return sqrt(x**2 + y**2)

nesting the import in the function keeps the outer namespace clear. However, does the import actually occur on every call to the function and thus decrease performance or only on the first call and then somehow cached?

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
  • @BrenBarn Thanks, but then at least close it as duplicate of the _open_ question https://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module of which _that_ is considered a duplicate... – Tobias Kienzler Aug 24 '16 at 05:57
  • ...though personally I like [Alex Martelli's answer](https://stackoverflow.com/a/3095167/321973) best – Tobias Kienzler Aug 24 '16 at 05:59
  • 1
    I was actually the one who first suggested the duplicate. I found the question (especially "Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run?") and its answers to be more relevant to your question than the question it is a duplicate of. – Karin Aug 24 '16 at 06:10
  • @Karin Thanks, upon closer inspection that makes sense. – Tobias Kienzler Aug 24 '16 at 06:12

0 Answers0