Which of the best choice ?

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Tue Nov 11 18:50:49 EST 2003


On 11 Nov 2003 15:54:50 -0800, SungSoo, Han wrote:
> There are two coding style when python import module.

This is more than coding style; it has two distinct effects.

>  (1) import sys

Allows 'sys' module objects to be used within the 'sys' namespace.

>  (2) from import sys (or from import *)

Isn't syntactically correct (refers to a non-existent module called
'import', then has the non-keyword 'sys').  Assuming you mean:

    from sys import *

this has the effect that all objects from the 'sys' module are available
in the default namespace.

> I prefer (1) style. Because it's easy to read, understand module in
> any category

More importantly, (1) doesn't pollute the main namespace; any objects
that have the same name in the main namespace are unambiguously
referenced with the 'sys' namepace.

    >>> maxint = 23
    >>> maxint
    23
    >>> import sys
    >>> maxint
    23
    >>> sys.maxint
    2147483647

Whereas, with (2), the symbols from 'sys' pollute the main namespace:

    >>> maxint = 23
    >>> maxint
    23
    >>> from sys import *
    >>> maxint
    2147483647

> Which prefer ?

It's usually preferable to use (1), because there is no namespace
collision, and it has the added benefit of making it unambiguous which
module the symbols come from when they are later used.

-- 
 \        "Why, I'd horse-whip you if I had a horse."  -- Groucho Marx |
  `\                                                                   |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list