Neena Vivek Neena Vivek - 1 year ago 67
Python Question

What's the correct way for importing the whole module as well as a couple of its functions in Python?

I know that

from module import *
will import all the functions in current namespace but it is a bad practice. I want to use two functions directly and use
when I have to use any other function from the module. What I am doing currently is:

import module
from module import func1, func2

Is it a good practice? Does the order of first two statements matter?
Is there a better way using which I can use these two functions directly and use rest of the functions as usual with the module's name prepended to them?

Using just
import module
results in very long statements with a lot of repetition if I use the same function from the given module five times in a single statement. That's what I want to avoid.

Answer Source

It is not good to do (may be opinion based):

import module

from module import func1, func2  # `func1` and `func2` are already part of module

Because you already hold a reference to module.

If I were you, I would import it in the form of import module. Since your issue is that module.func1() becomes too long. I may import the module and use as for creating a alias for the name. For example:

import module as mo
#                 ^ for illustration purpose. Even the name of 
#                   your actual module wont be `module`. 
#                   Alias should also be self-explanatory 

# For example:
import database_manager as db_manager

Now I may access the functions as:


Edit: Based on the edit in actual question

If your are calling same function in the same line, there is possibility that your are already doing some thing wrong. It will be great if you can share what your that function does.

For example: Want to the rertun value of those functions to be passed as argument to another function? as:

test_func(mo.func1(x), mo.func1(y). mo.func1(z))

could be done as:

params_list = [x, y, z]
func_list = [mo.func1(param) for param in params_list]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download