1

So I'm writing a small program in Python. It's not going to be very demanding and is for fun so doesn't necessarily need to be optimized for speed or resources or any of that and I'm far from pro so if this is a ridiculous question sorry, BUT I am curious:

I am defining several small functions (like 5 lines) that will need libraries to be imported (urllib, xml.etree, etc.). Is there a reason to do them outside of the function, like at the beginning of my code, instead of as the first lines of the function? I would think that having it in the function would make it easier to steal those functions effectively in the future but I was also thinking it my slow down things a bit. Is there any hard and fast rule or rule of thumb here? And if not, does anyone have any opinions?

kmdewey
  • 61
  • 7

1 Answers1

7

Actually, importing the modules locally inside a function would improve efficiency (slightly). Looking up local names is always faster than looking up globals because the global namespace is one of the last that Python checks when searching for a name.

That said, I wouldn't recommend doing this for three reasons:

  1. It wastes lines of code. Every function which needs a particular module will have to import it. This means that you will have a lot of repeated import statements.

  2. It makes the dependencies of your code hard to find. One of the main reasons that you import at the top of a file is so that the imports are easily visible.

  3. It goes against PEP 0008, which specifically says:

    Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.