graffaner
graffaner

Reputation: 155

does import module(or package).function actually import the whole module / package?

Say I want to

import module.function

does it actually imported the whole module into memory instead of just the function?

I want to ask this question because I thought only importing the function I need from a module reduces memory consumption.

Edit
Clarify my question and ask it in the following two contexts:
1. import module.function1 where module is a single module.py file which contains function1 and other functions definition and classes definition etc. Is the whole module loaded into memory or just the function1 definition part?
2. import package.function1 where package is a package like numpy where it contains file hierarchy, like Mike Tung described below. Is the whole package loaded into memory, or just the module file that contains the function1 definition, or just the part of that module file which defines function1?

Upvotes: 3

Views: 754

Answers (4)

Nick Weseman
Nick Weseman

Reputation: 1532

Yes, it does import the whole function. The purpose of including the function is mostly for code style purposes. It makes it easier to understand that you are only using that specific function in the module.

Whether 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 impact on memory/performance.

Upvotes: 4

user2357112
user2357112

Reputation: 280857

import module.function is an error, actually. You can only import submodules, not functions, with that syntax.

from module import function is not an error. from module import function would execute the entire module, since the function may depend in arbitrarily complex ways on the other functions in the module or arbitrary setup executed by the module.

Upvotes: 2

Mike Tung
Mike Tung

Reputation: 4821

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 are saying import all the py files under foo for use in app.py

when you say:

import foo.foo1

you are saying I only want the contents of foo1.py

When you say:

from foo.foo2 import *

you are saying take all the stuff in foo2 and dump it in to the same namespace as app.py.

In scenario 1 you would have to qualify all your calls extremely specifically.

foo.foo1.function()

In scenario 2

foo1.function()

In scenario 3

function()

Ideally you would be using scenario 2 as it is a nice middle ground and helps to prevent namespace pollution.

Upvotes: 2

d512
d512

Reputation: 34113

This post indicates that the entire module is still imported even if you are only using a small part of it.

Upvotes: 1

Related Questions