On Mon, Jan 17, 2011 at 2:01 AM, frank cui <frankcu...@gmail.com> wrote: > Hi all, > > I'm quite a novice in doing python,and i wish to ask you guys a question on > the module import. > > Say we have a source file called module1.py. > > What's the difference between the " import module1 " and " from module1 > import * " > > I know that conventionally by coding style, we dont use the second form,but > does the first one also reach the same effect ? (importing all the classes > and functions and pollute the namespace?)
No, not at all. Only the second form pollutes the namespace. The first form *only* imports the name "module1" into your namespace. To access stuff in module1, you then *must* write "module1.foo" etc., explicitly going thru the "module1" name every single time.† The latter form dumps *all* the stuff in module1 into your namespace,‡ with the name "module1" itself left unbound. To access stuff from module1, you then merely write "foo" etc., and are unable to refer to the module namespace as a whole. By way of example: $ python Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00) >>> import pickle >>> dir(pickle) # output severely trimmed for convenience/relevance [..., 'dump', 'dumps', 'encode_long', 'format_version', 'load', 'loads', ...] >>> dump Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'dump' is not defined >>> pickle.dump <function dump at 0x4649b0> >>> pickle <module 'pickle' from '/sw/lib/python2.6/pickle.pyc'> Contrast with: $ python Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00) >>> from pickle import * >>> dump <function dump at 0x4649b0> >>> pickle.dump Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pickle' is not defined >>> pickle Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pickle' is not defined †: Unless you manually alias something to a local name of course, but that's not pedagogically relevant here. ‡: Excepting names starting with an underscore. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list