9

As a newbie, I've grown fond of importing modules almost by default when I start writing something just because I call on certain functions within them quite a bit (modules like random, time, os, and sys). However, does this impact performance at all? If I only want a specific function in the module, am I better served by asking for it explicitly or should I not care?

1 Answer 1

9

When you do from module import name, Python still has to run module, so there is no difference performance-wise.

Generally, if you are only using one thing from a module, the using from x import y is fine, but otherwise, using import x and then x.y results in a lower chance of conflicting names.

The reason for this is that Python doesn't treat functions and classes specially. When you import from a module, all you are doing is taking objects from that module and using them. This is useful, as it makes modules (as well as classes and functions) extremely flexible, but it does mean that Python has to run the whole script for a module before it can import from it (naturally, module writers can work around this by using the if name == "main": idiom to insert code that shouldn't be run on import).

6
  • 1
    What if I use "from module import *" ?
    – Kimomaru
    Feb 28, 2013 at 20:39
  • @Kimomaru That's generally a bad idea, unless the module was specifically designed for it. In most cases, it just pollutes your namespace and makes it harder to work with the code. Naturally, it still loads the whole module as the other methods do. Feb 28, 2013 at 20:40
  • Interesting. So, it's better to be as specific as I can be because it will keep things organized. I can imagine importing everything, then accidentally creating a function named identically to something imported - would cause a problem.
    – Kimomaru
    Feb 28, 2013 at 20:43
  • @Kimomaru Essentially, yes. Not to mention one module could have something with the same name as another module. People often accidentally call a variable list for example, and then get into trouble when they try to use the list() built-in later. The more you import into the namespace, the more issues like this are likely to crop up. Feb 28, 2013 at 20:44
  • Very interesting. Okay, will make note. Thanks, Lattyware.
    – Kimomaru
    Feb 28, 2013 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.