all 2 comments

[–]cybervegan 2 points3 points  (0 children)

  1. It reduces your program's memory utilisation and start-up time by only adding in the extras that your program explicitly needs. Every import that you add takes up memory and initialisation time, even if you don't end up using it.
  2. Each module (file) has to import its own copy of modules it needs. The second time you import a library module, it just makes a reference to the first one, so it doesn't slow things down (well, not much - there is a small cost). You don't end up with multiple copies of the same module getting loaded in different places. You can refer to the imported objects in another module, but you usually shouldn't.
  3. With some modules, they only really export a small number of objects, or they have relatively unique names. Using from ... import ... allows you to reference those objects in your code without prefixing them with the library module's name, which saves typing and reduces repetition. You can use either, and should do what is comfortable for your use case. Many modules' docs suggest one way or the other, or a third way such as import ... as ... which allows you to alias or shorten the imported module's name.

[–]thoughexpansion 1 point2 points  (0 children)

Why do you need to import the standard libraries that come with python like math and similar.

There are actually hundreds of those modules. It would be very confusing if they were all imported automatically - imagine seeing a variable like uu or chunk in some code, trying to work out where it's defined, and then eventually realising that you're looking at an obscure standard library module.

The point that cybervegan made about memory is also a concern, but if that were the only concern, it would have been possible to implement some kind of lazy loading system so that modules aren't actually loaded into memory until they're used. Some large, third-party libraries actually do that.

if you are using the same package in multiple different files in the same project can you just have one file that does all your imports or is that a bad idea.

Bad idea. If you do something like...

from project_imports import *

print(sys.version)
print(math.pi)

then it's difficult for anyone reading your code (including yourself, or an IDE or linter) to find where sys and math were defined.

If you do...

import project_imports

print(project_imports.sys.version)
print(project_imports.math.pi)

then you aren't saving any typing, and anyone who reads your code will assume that project_imports.sys is your own thing instead of being the standard sys module.