Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between these 2 imports?

Tags:

python

Do the below 2 import statements have some difference? Or just the same thing?

from package import *

import package
like image 386
Thomson Avatar asked Aug 23 '11 16:08

Thomson


2 Answers

from package import * imports everything from package into the local namespace; this is not recommended because it may introduce unwanted things (like a function that overwrites a local one). This is a quick and handy import tool, but if things get serious, you should use the from package import X,Y,Z, or import package syntax.

import package imports everything from package into the local package object. So if package implements the something() function, you will use it by package.something().

Also, another thing that should be talked about is the nested namespace case: suppose you have the function package.blabla.woohoo.func(), you can import package.blabla.woohoo and use package.blabla.woohoo.func(), but that is too complicated. Instead, the easy way to do it is from package.blabla import woohoo and then use woohoo.func() or from package.blabla.woohoo import func, and then use func(). I hope this makes sense. If it doesn't, here's a code piece to illustrate:

import package.blabla.woohoo
package.blabla.woohoo.func()

from package.blabla import woohoo
woohoo.func()

from package.blabla.woohoo import func
func()

Hope this helps :)

like image 185
Gabi Purcaru Avatar answered Oct 03 '22 07:10

Gabi Purcaru


The difference is the use of a namespace for the package.

from package import *
class_in_package()

vs

import package
package.class_in_package()
like image 29
TorelTwiddler Avatar answered Oct 03 '22 08:10

TorelTwiddler