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?
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?
The only reason that I could think is that you want to change from
from spam import *
toimport spam as sp
. If you would just replace those lines, it would instantly break the code, you would have to prefix everything withsp.
. If you want to do this change at a slower pace, you can do this. Then you can slowely add thesp.
where needed and eventually remove thefrom spam import *
.No. Since you have imported
spam
with namesp
and then imported everything usingfrom 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 callsomefunction()
withsp.somefunction()
Since
from spam import *
it can be called directlysomefunction()
so why usesp.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 usesp.somefunction()
,sp.someotherfunction()
.When you import spam as sp, you make sure that there are no conflicts with other import commands:
This is working as expected, but this isn't:
When you avoid this problem by using
import spam as sp
, why would you want to usefrom spam import *
anyways? I don't think there is any point in this.import spam as sp
will load the module and put it into the variablesp
.from spam import *
will load the module and all its attributes (classes, functions, etc...) and also the ones that are imported with a wildcard intospam
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 withimport 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 lotimport spam as sp
and usesp.func1()