Imports a module (or package) .function actually imports the whole module / package?
Let's say I want
import module.function
did it really import everything module
into memory instead of just function
?
I want to ask this question because I thought that only importing a function that I need from a module reduces memory consumption.
Edit
Refine my question and ask it in the following two contexts:
1. import module.function1
where module
is the only file module.py
that contains the definition of function1
both other functions and the definition of classes, etc. Does it load all module
or only part of the definition into it function1
?
> 2. import package.function1
where package
is a package such as numpy
where it contains a file hierarchy like Mike Tung described below. Is the entire package loaded into memory, or just the module file that contains the definition function1
, or just the part of that module file that defines function1
?
source to share
Let's say you have the following structure
app/
├── foo/
│ ├── __init__.py
│ ├── foo1.py
│ └── foo2.py
├── bar/
│ ├── __init__.py
│ └── bar1.py
└── app.py
When you say in app.py
import foo
you say you import all py files under foo for use in app.py
when you speak:
import foo.foo1
you say i only want the contents of foo1.py
When you speak:
from foo.foo2 import *
you say take all things in foo2 and dump it into the same namespace as app.py.
In scenario 1, you will need to qualify all your calls extremely specifically.
foo.foo1.function()
In scenario 2
foo1.function()
In scenario 3
function()
Ideally, you would use scenario 2, as it is a good staging area and helps prevent namespace pollution.
source to share
Yes, it will import the whole function. The purpose of including a function is mainly for code style purposes. This makes it easier to understand that you are only using this function in a module.
do you use
import module
or
import module.function
# this is equivalent to "import module" since you will still have to type
# "module.function()" to use the function. See next answer for correct syntax
or
from module import function
has little memory / performance impact.
source to share
import module.function
- this is mistake. You can import submodules, not functions, with this syntax.
from module import function
is not an error. from module import function
will execute the whole module, since the function can depend in arbitrarily complex ways on other functions of the module or on an arbitrary setting performed by the module.
source to share