Is there a point to import the same module in two

2019-02-26 07:07发布

Is there a point to import as both wildcard and non-wildcard manner like:

import spam as sp
from spam import *

in the very same file?

4条回答
唯我独甜
2楼-- · 2019-02-26 07:23

The only reason that I could think is that you want to change from from spam import * to import spam as sp. If you would just replace those lines, it would instantly break the code, you would have to prefix everything with sp.. If you want to do this change at a slower pace, you can do this. Then you can slowely add the sp. where needed and eventually remove the from spam import *.

查看更多
▲ chillily
3楼-- · 2019-02-26 07:31

No. Since you have imported spam with name sp and then imported everything using from spam import * sp will never be used and is therefore unnecessary.

For example if we have a function called somefunction(). import spam as sp would mean we could call somefunction() with sp.somefunction()

Since from spam import * it can be called directly somefunction() so why use sp.somefunction() instead.

from spam import * is considered extremely bad practice. You should import each function individually rather than do that. (from spam import somefunction, from spam import someotherfunction and so on). Or you could just use sp.somefunction(), sp.someotherfunction().

查看更多
beautiful°
4楼-- · 2019-02-26 07:33

When you import spam as sp, you make sure that there are no conflicts with other import commands:

import spam as sp
import myfunctions as my

sp.foo()
my.foo()

This is working as expected, but this isn't:

from spam import *
from myfunctions import *


foo()
foo() #Which foo() is meant? UNCLEAR!!!

When you avoid this problem by using import spam as sp, why would you want to use from spam import * anyways? I don't think there is any point in this.

查看更多
Ridiculous、
5楼-- · 2019-02-26 07:33

import spam as sp will load the module and put it into the variable sp. from spam import * will load the module and all its attributes (classes, functions, etc...) and also the ones that are imported with a wildcard into spam will be accessible.

import * is a shortcut when you have a lot of classes, functions you need to access. But it is a bad practice (cf PEP) since you do not encapsulate imported attributes into a namespace (and it's what you do with import spam as sp) and can lead to unwanted behavior (if 2 functions have the same name in your main program and into spam)

The best practice, and what states clearly what you'll use is from spam import func1, func2 or if you will use it a lot import spam as sp and use sp.func1()

查看更多
登录 后发表回答