What does "from ... import ..." mean?
If you do import sys
, you'll get to access the functions and variables in the module sys via sys.foo
or sys.bar()
. This can get a lot of typing, especially if using something from submodules (e.g. I often have to access django.contrib.auth.models.User
).
To avoid such this redundancy, you can bring one, many or all of the variables and functions into the global scope. from os.path import exists
allows you to use the function exists()
without having to prepend it with os.path.
all the time.
If you'd like to import more than one variable or function from os.path, you could do
from os.path import foo, bar
.
You can theoretically import all variables and functions with from os.path import *
, but that is generally discouraged because you might end up overwriting local variables or functions, or hiding the imported ones. See What's the difference between "import foo" and "from foo import *"? for an explanation.
from module import x
means:
Load the module named module
, but only fetch x
into the current namespace.
In bonehead terms this means,
from USA import iPhone # instead of importing the whole USA for an iPhone you now will just import the iPhone into your program,
Why do you need something like this ?
consider this, without the from ... import statement your code will look like this
import USA
variableA = USA.iPhone()
with the from ... import statement it looks like,
from USA import iPhone
variableA = iPhone()